簡體   English   中英

將多個值從PHP URL傳遞到SQL表中的一行

[英]Passing multiple values from a PHP URL to a single row in a SQL table

我正在嘗試使用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
?>

date變量總是傳遞給數據庫,但fname是以NULL結尾的變量。 我有點感覺這是語法上的問題,但是對於PHP來說我還是很新。

基本上,我認為這是問題所在:

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

感謝您的幫助。

謝謝。

嘗試這個...

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

有時那些多余的引號可以解決問題...大聲笑

但是Colin也是正確的。...這里的漏洞很明顯。 希望你只是在測試東西.. :)

請使用PDO或MySQLi代替mysql_*函數。 我喜歡PDO,可以在這里找到有用的信息: http : //wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developershttp://us.php.net/manual/zh/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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM