1

我正在使用电动小鬼 + MySQL 数据库。我正在尝试使用 PHP 将我的 imp 值传递给 MySQL,但它显示空白条目,知道为什么吗?我尝试了一切,但无法弄清楚发生了什么。

PHP

<?php

// Set your default timezone
define('DB_NAME', 'db_name');
define('DB_USER', 'db_user');
define('DB_PASSWORD', 'db_pass');
define('DB_HOST', 'db_host');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link)
{
    die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

//read the json file contents
$jsondata = file_get_contents('value');

//convert json object to php associative array
$data = json_decode($jsondata, true);

//get info
$status = $data['status'];

if (!$db_selected)
{
    die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}

$value = $_POST ['status'];

$sql = "INSERT INTO imp (status) VALUES ('$value')";

if (!mysql_query($sql))
{
    die('Error: ' . mysql_error());
}

echo "<h5>Message Successfully Sent!</p></h5>";

mysql_close();

?>
4

1 回答 1

0

您可以使用 PDO 和prepared statements 使用类似以下的内容来避免 SQL 注入:

define('DB_HOST', 'your_host');
define('DB_NAME', 'your_db_name');
define('DB_USER', 'your_username');
define('DB_PASSWORD', 'your_password');

try {
    //Make your connection handler to your database
    $conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

    $jsondata = file_get_contents('value');

    //convert json object to php associative array
    $data = json_decode($jsondata, true);

    //get info
    $status = $data['status'];
    $value = $_POST['status'];


    $sql = "INSERT INTO imp (status) VALUES (:status)";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':status'=>$value));

    if ($stmt->rowCount() > 0) {
        echo "<h5>Message Successfully Sent!</p></h5>"; 
    }

} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}
于 2015-11-12T20:23:33.767 回答