我的代码应该是每个$ age变量的值,而是它回应“age”这个词?

时间:2012-06-19 00:01:21

标签: php mysql

这是我正在使用的代码:

<?php
// Set the MySQL Configuration
$db_host       = "";
$db_user       = "";
$db_password   = "";
$db_name       = "";
$db_table      = "";

// Start Connection
$db_connect        =  mysql_connect ($db_host, $db_user, $db_password);

// Select Database
$db_select        =  mysql_select_db ($db_name, $db_connect);

// Update Values in Database


$query         = "UPDATE $db_table SET

    age  =  age + 1,

    land = '".$_POST['data3']."'

    WHERE name = '".$_POST['data1']."'

    ";


// Execution MySQL query        
$result =  mysql_query($query) or die(mysql_error($db_connect));

//Close MySQL connection
mysql_close($db_connect);

//HTTP Response
echo " your age: age";

?>

我想回应$age变量的值,但我总是得到“年龄”这个词。例如,代码应该回显your age: 5,而是输出your age: age

1 个答案:

答案 0 :(得分:3)

首先,您需要运行SELECT查询以检索age的更新值。查询应如下所示:

"SELECT age FROM db_table_name WHERE name = ?"

获得该查询的结果后,请说PDO::fetch(请参阅下面有关PDO的说明)并将其设置为变量$age,您可以使用echo语句输出它:

echo "Your age: $age";

另外,请不要将mysql_*函数用于新代码。它们已不再维护,社区已开始deprecation process(请参阅red box)。相反,您应该了解prepared statements并使用PDOMySQLi。如果您无法确定哪个,this article会对您有所帮助。如果您想学习,this is a good PDO tutorial

我没有为您提供确切代码的原因是因为不应该使用mysql_*函数来完成。直接从$_POST创建一个包含数据的SQL查询,这是非常危险的代码,并且是一个非常糟糕的想法。永远不要这样做。你可以打开很多SQL注入攻击。即使使用mysql_real_escape_string也是不够的。你应该使用准备好的陈述。

更新:这是一个简单的示例,它接近您所要求的,但使用PDO和预处理语句。这绝不是一个全面的例子,因为有几种方法可以改变它仍然可以工作(例如,预处理语句允许你在一个语句中在服务器上执行多个语句),并且我没有一个工作服务器测试的时刻,以确保它完全你需要什么,但我希望它得到了重点。

<?php

// Create the database connection
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');

// Set PDO/MySQL to use real prepared statements instead of emulating them
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

// The UPDATE query we're going to use
$update_query = "UPDATE `db_table_name` SET age = age + 1, land = :land WHERE name = :name";

// Prepare the query
$stmt = $db->prepare($update_query);

// Bind variables to the named parameters in the query with their values from $_POST
$land = $_POST['data3'];
$name = $_POST['data1']
$stmt->bindParam(':land', $land);
$stmt->bindParam(':name', $name);

// Execute the statement on the server
$stmt->execute();

// The SELECT query we're going to use
$select_query = "SELECT age FROM `db_table_name` WHERE name = :name";

// Again, prepare the query
$stmt_select = $db->prepare($select_query);

// Bind the paramters (in this case only one) to the new statement
// $name is already set from before, so there is no need to set it again
$stmt_select->bindParam(":name", $name);

$stmt_select->execute();

/*
 * With no arguments, PDO::fetchColumn() returns the first column
 * in the current row of the result set. Otherwise, fetchColumn()
 * takes a 0-indexed number of the column you wish to retrieve
 * from the row.
*/
$age = $stmt_select->fetchColumn();

echo("Your age: $age");
?>

所有这些信息都直接来自prepared statementsPDO::fetchColumn()上的PHP文档。