2017-10-16 199 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);