为什么MySQL数据库注册空白?

时间:2015-11-12 20:13:43

标签: php mysql imp

我正在使用电子imp + 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();

?>

1 个答案:

答案 0 :(得分:0)

您可以使用PDO和预编译语句来使用以下内容来避免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();
}