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



我正在使用electrical 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();
?>

您可以使用类似以下的方法使用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();
}

相关内容

  • 没有找到相关文章

最新更新