PHP插入到MySQL查询尝试返回Null

时间:2014-02-03 21:01:22

标签: php mysql

我在使用PHP insert into语句向MYSQL表添加新行时遇到了一些困难。我已经授予远程用户所有权限,并且我能够查看表格。但是,当我尝试插入表时,我也得到A NULL返回。有什么建议吗?

以下是代码:

<?php
$ID1=$_REQUEST["ID1"];
$ID2=$_REQUEST["ID2"];
$ID3=$_REQUEST["ID3"];
$ID4=$_REQUEST["ID4"];
$ID5=$_REQUEST["ID5"];
$return = "0";

$link = mysql_connect('my-remote-server', 'root', 'pwd');
if (!$link) {echo $return; $end ="1";}

$db_selected = mysql_select_db($ID3, $link);
if (!$db_selected) {echo $return; $end ="1";}

if ($end != "1") 
{
    if (($ID5 == "1") && ($ID4 == "%%%"))
    {
        $check = mysqli_query($link,"INSERT INTO Students (NetID, GroupID)
        VALUES ('%s', '%s')",
        mysql_real_escape_string($ID1),
        mysql_real_escape_string($ID2));
        echo var_dump($check);
        echo "1";   

     }
}

1 个答案:

答案 0 :(得分:2)

像我们在最初的评论中所说的那样,坚持一个扩展名:mysql或MySQLi。在这种情况下,由于在PHP 5.3 +中弃用了mysql扩展,我强烈建议使用MySQLi。

您的代码可以通过修改为:

来更改(并使其更加安全)
<?php
$ID1=$_REQUEST["ID1"];
$ID2=$_REQUEST["ID2"];
$ID3=$_REQUEST["ID3"]; // database name apparently ?
$ID4=$_REQUEST["ID4"];
$ID5=$_REQUEST["ID5"];
$return = "0";

$db = new mysqli('my-remote-server', 'root', 'pwd', $ID3);

if($db) {
   if (($ID5 == "1") && ($ID4 == "%%%")) {
        $statement = $db->prepare("INSERT INTO Students (NetID, GroupID) VALUES (?, ?)"); // prepare the query, this prevents SQL injection
        $statement->bind_param('ss', $ID1, $ID2); // this tells MySQLi that the 2 variables are strings and should be properly escaped to fit in the query (automatically)
        $statement->execute(); // run the actual query
   }
}