当我尝试更新我的数据库以更改现有用户的位置时,我会收到所需的回显中的文本,但不会更改用户的详细信息。 这是我的代码 - 服务器详细信息已被删除以保护隐私。
{
$server = '';
$connectionInfo = array("Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
date_default_timezone_set('Europe/London');
$username = $_POST['username'];
$location = $_POST['location'];
$dateAndTime = date('d-m-y h:i a', time());
$selection_query = "SELECT 1 FROM users WHERE username = '".$username."'";
$result = sqlsrv_query($conn, $selection_query, array($username));
if (sqlsrv_fetch_array($result) == 0)
{
echo "Username does not exist.";
}
else
{
$updateUserQuery = "UPDATE users SET location='$location' datetime='$dateAndTime' where username='$username'";
sqlsrv_query($conn, $updateUserQuery);
echo $username;
echo "'s location has been successfully updated to ";
echo $location;
echo " at ";
echo $dateAndTime;
echo ".";
}
sqlsrv_close($conn);
}
答案 0 :(得分:0)
因此,在查看代码时,应该先检查以确保连接存在,然后再尝试进行查询。有点像这样:
// Create connection
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connected successfully";
这很重要b / c可能不是您的查询没有返回任何结果,而是您根本没有连接。
完成后,在查询中更改此行
$selection_query = "SELECT * FROM users WHERE username = '".$username."' LIMIT 1";
同样遵循Jay Blanchard在评论中所说的,这种编写查询的方式让你对SQL Inchections开放。这是一种用户在查询中编写您不希望运行的查询的方法。有点喜欢&#34; DROP All Tables&#34;查询。永远不会允许。他的链接是一个好主意。