2017-10-16 138 views
0

我發現下面的腳本出於某種原因掛起。它會加載和PHP沒有看到任何錯誤,但它不會處理數據(注意我們是在我有一個單獨的登錄數據庫打開的情況下)。爲什麼下面不顯示打開SQL連接?

在process.php中,我們有以下內容:

<? PHP 
//Process the POST data in prepration to write to SQL database. 
$_POST['chat_input'] = $input; 
$time = date("Y-m-d H:i:s");  
$ip = $_SERVER['REMOTE_ADDR']; 
$name = $_SESSION['username'];  
$servername = "localhost"; 
$username = "id3263427_chat_user"; 
$password = "Itudmenif1!Itudmenif1!"; 
$dbname = "id3263427_chat_user"; 
$id = "NULL"; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 

if($link === false){ 
    die("ERROR: Could not connect. " . mysqli_connect_error()); 
} 

$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`, 
     `message`) VALUES ('$id','$name', '$ip', '$time', '$input')'; 

if(mysqli_query($link, $sql)){ 
    mysqli_close($conn); 
    header('Location: ../protected_page.php'); 
} else { 
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); 
} 

?> 

傳遞到上面的腳本的HTML格式如下:

<form action="/process.php" method="post" id="chat"> 
    <b> Send A Message (500 Character Max):</b><br> 
    <textarea name="chat_input" form="chat" size="500"></textarea> 
    <input type="submit" value=submit> 
</form> 

不知道發生了什麼事與此有關。

+0

你確定要做這個'$ _POST ['chat_input'] = $ input;'而不是'$ input = $ _POST ['chat_input'];'? – pmahomme

+0

我糾正了這一點,對任何事情都沒有任何影響。 –

+0

你確定沒有錯誤報告檢查你的sql字符串它必須被雙引號包圍,如果你簡單的列名稱報價 – douxsey

回答

2

您得到了語法錯誤,因爲您正在使用您的'在$ id之前關閉$ sql字符串。

這是關於你的$ id變量的?使用您當前的代碼,您將插入字符串「NULL」。如果你想設置sql值null,你應該使用​​或者不要插入任何值。

如果你想讓你的數據庫設置一個ID,也可以留空。

$input = $_POST['chat_input']; 
$id = null; 

$conn = new mysqli($servername, $username, $password, $dbname); 

if($conn->connect_error){ 
    die("ERROR: Could not connect. " . $conn->connect_error); 
} 

首先解決

如果這不是一個產品代碼,你可以直接插入變量到語句,但你應該使用"而不是'您的SQL字符串,這樣你就可以插入變量和'而不關閉字符串。

$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')"; 
if($conn->query($sql) === true) { 
$conn->close(); 
header('Location: ../protected_page.php'); 
} else { 
echo "ERROR: Could not able to execute $sql. " .$conn->error; 
$conn->close(); 
} 

解決方法二

一個更好的方法將是一個事先準備好的聲明。

$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)'); 
$stmt->bind_param("ssss", $username, $ip, $time, $input); 

if($stmt->execute()) { 
$stmt->close(); 
$conn->close(); 
header('Location: ../protected_page.php'); 
} else { 
echo "ERROR: Could not able to execute $stmt. " . $conn->error; 
$stmt->close(); 
$conn->close(); 
} 

bind_param()"s"在給定位置定義字符串,如果要插入一個整數,使用"i"代替。

例如bindParam("sis", $string, $integer, $string);