2012-09-07 118 views
0
$user = mysql_real_escape_string($_POST["userlogin"]); 

    mysql_connect("uritomyhost","myusername","password"); 
    mysql_select_db('mydatabase'); 
    mysql_query('UPDATE table SET field = field + ($userlogin)'); 

这是从发布请求中获取userlogin然后将其插入到我的SQL查询中的正确方法吗?将PHP变量传递给SQL查询

+0

它使用带有用户提供值的数据库字段的值是什么? –

回答

0

使用mysql_real_escape_string() MySQL连接后 使用双引号

mysql_query("UPDATE table SET field = field + ({$userlogin})"); 
+0

要添加此,使用单引号时,[变量不会展开](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single)** *编辑***:它也好像你调用变量'$ user'而不是'$ userlogin'。 – h2ooooooo

0

你应该只连接到数据库后使用mysql_real_scape_string()...
使你的代码改成这样:

mysql_connect("uritomyhost","myusername","password"); 
mysql_select_db('mydatabase'); 
$userlogin = mysql_real_escape_string($_POST["userlogin"]); 
mysql_query("UPDATE table SET field = '$userlogin'"); 
0

试试这个。

$user = mysql_real_escape_string($_POST["userlogin"]); 

mysql_connect("uritomyhost","myusername","password"); 
mysql_select_db('mydatabase'); 
mysql_query("UPDATE table SET field = value where user='$user'"); 
0

使用mysqli_query为您查询(注意),并用准备好的语句。使用预处理语句比使用直接查询并在查询字符串中包含变量更安全。而且,mysql很快就会被弃用。例如:

<?php 
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 
/* check connection */ 
if (mysqli_connect_errno()) { 
printf("Connect failed: %s\n", mysqli_connect_error()); 
exit(); 
} 
$city = "Amersfoort"; 
/* create a prepared statement */ 
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) { 

/* bind parameters for markers */ 
$stmt->bind_param("s", $city); 

/* execute query */ 
$stmt->execute(); 

/* bind result variables */ 
$stmt->bind_result($district); 

/* fetch value */ 
$stmt->fetch(); 

printf("%s is in district %s\n", $city, $district); 

/* close statement */ 
$stmt->close(); 
} 
/* close connection */ 
$mysqli->close(); 
?> 
+0

Mysqli在使用这种方式时并不安全。 Mysqli只有在使用[prepared statements](http://www.php.net/manual/en/mysqli.prepare.php)时更加安全,就像[PDO](http://php.net)一样。 /manual/en/book.pdo.php) – h2ooooooo

+0

是的,抱歉忘了提及那个,编辑我的答案。感谢提醒 – harshit

+0

哦,现在我明白了! – user1431627

0

试试这个

mysql_query("UPDATE table SET field = field + ('$user')"); 

然而,

,因为你没有在那里你UPDATE条款你可能会更新表中的所有字段

不应该它应该是

mysql_query("UPDATE table SET field = field WHERE user= '$user'"); 
0

我想你想INSERT而不是使用Update。为什么field = field + ($userlogin)?这将连接值。还有一两件事,请使用PDOMYSQLI

示例使用PDO扩展:使用过时的功能

<?php 

    $stmt = $dbh->prepare("INSERT INTO tanlename (field) VALUES (?)"); 
    $stmt->bindParam(1, $user); 
    $stmt->execute(); 

?> 
+0

它应该计入当前值? – user1431627

5

停止并使用PDO来代替。

$stmt = PDO::prepare('UPDATE table SET field = field + :field'); 
$stmt->execute(array('field' => $_POST["userlogin"])); 

阅读information about PDO。简而言之:它为你逃避了你的数据,在数据库中是非常一致的,而且一般来说更简单。

+0

我应该如何连接到它?这只能得到它的价值并插入它。如何使用此代码登录到我的数据库? – user1431627

+0

你会使用[__construct](http://www.php.net/manual/en/pdo.construct.php)。请参阅该页面上的示例:) –

+0

如何定义它? – user1431627