dqtok88424 2015-07-26 13:07
浏览 62
已采纳

在函数外部使用变量

this is probebly a silly question but I don't know where else to ask this. I need to call on $conn in the functions below, but if I try to turn it into a global it doesn't work. If someone can explain to me how to use an outside variable inside a function I'd be very grateful.

Here's my little piece of code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
 //Maak connectie met database
 $host = "localhost";
 $username = "i266161_studie";
 $password = "studie";
 $dbnaam = "test";
 $fout = "Error: Failed to open database";

 $conn = mysqli_connect($host, $username, $password, $dbnaam)
 or die ("Connection failed: ".mysqli_connect_error()); 

function insert_once($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Henk", 17, "Eindhoven")';
mysqli_query($conn,$query);
}

function insert_twice($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Bert", 21, "Helmond"), ("Ruud", 32, "Helmond")';
mysqli_query($conn,$query);
}
insert_twice();

?>
  • 写回答

2条回答 默认 最新

  • dongwen1909 2015-07-26 14:41
    关注

    don't use globals unless you REALLY have to! don't forget to pass your $conn parameter to your functions e.g.

    change this:

    insert_twice();
    

    to this:

    insert_twice($conn);
    

    I'd suggest adding some error handling to your mysql_query() calls too, you should not assume that these are always successful

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误