1

我正在尝试使用 Get 语句从 PHP URL 传递多个值。我觉得应该很简单。我设法很好地传递了一个变量,但由于某种原因,第二个变量总是最终为 NULL。

这是我的代码:

<?php

$DB_HostName = "localhost";
$DB_Name = "prototype3DB";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "sqlTable";


if (isset ($_GET["date"]))
$date = $_GET["date"];
else
$date = "null";

    if (isset ($_GET["fname"]))
    $fname = $_GET["fname"];
    else
    $fname = "null";


    $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
    mysql_select_db($DB_Name,$con) or die(mysql_error()); 


    $sql = "insert into $DB_Table (date, fname) values ('$date','$fname')";

    $res = mysql_query($sql,$con) or die(mysql_error());

    mysql_close($con);
    if ($res) {
        echo "success";
    }else{
        echo "failed";
    }// end else
?>

日期变量总是传递给数据库,但 fname 是最终为 NULL 的变量。我有点感觉这是语法问题,但我对 PHP 还是很陌生。

基本上,我认为这条线是问题所在:

$sql = "insert into $DB_Table (date, fname) values ('$date','$fname')";

我很感激任何帮助。

谢谢。

4

2 回答 2

0

试试这个...

$sql = "insert into $DB_Table (date, fname) values ('$date','".$fname."')";

有时那些额外的引号可以解决问题...大声笑

但 Colin 也是对的……这里的漏洞非常明显。希望你只是在测试东西.. :)

于 2013-04-04T19:31:40.050 回答
0

请使用 PDO 或 MySQLi 代替mysql_*函数。我喜欢 PDO,可以在这里找到有用的信息:http ://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers 和http://us.php.net/manual/en/pdostatement.bindvalue.php

要快速入门,请检查以下代码:

<?php

// Credentials. DSN is a string defining how to connect to the DB
$DB_DSN    = "mysql:dbname=myDatabase;host=127.0.0.1";
$DB_USER   = "myUser";
$DB_PASSWD = "myPassword";

// Make the connection and get a handle for talking to the db
$db = new PDO($DB_DSN, $DB_USER, $DB_PASSWD);

// Make query into a prepared statement. Protects us from SQL injection.
// Use placeholders like :status and :id where we will be inserting variables
$statement = $db->prepare('
    UPDATE users
    SET status = :status
    WHERE id = :id ');

// Associate vars with the placeholders in our query
// Define the type of valus such as string or int with the third param
$statement->bindValue(':id',     $_GET['id'],     PDO::PARAM_INT);
$statement->bindValue(':status', $_GET['status'], PDO::PARAM_STR);

// Actually run the query
$statement->execute();
于 2013-04-04T20:21:58.350 回答