php - 为什么MySQL数据库注册空白世纪?

标签 php mysql imp

我正在使用 electric 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 注入(inject):

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();
}

关于php - 为什么MySQL数据库注册空白世纪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680462/

相关文章:

mysql - 无法将 .SQL 文件迁移到 JawsDb (MySQL)

Objective-C 实现指针

pubnub - 电动 IMP + PubNub : Agent making extra calls

php - 从表中选择一系列行

PHP 哈希文件,CRC32b 或 MD5 更好?

php - 表格不显示空记录

Oracle imp 和 exp 命令

php - 使用准备好的语句将值插入数据库

mysql - 如何将相同类型的值分组为共同值并按该值分组

mysql - 如何按任意关键字排序?