更新MySQL有时只能工作。不是每一次

时间:2013-01-22 14:07:52

标签: php mysql forms

我正在制作一个非常简单的网站,它将在办公室的电视上播放。 index.php页面是一个表单,它有三个字段。表单方法是post,并且所有内容都是正确的。

然后我在下一页上有这段代码,提交后表格指向的那段。

 mysql_select_db("figs", $con);

mysql_query("UPDATE stats SET slots_sold=$_POST[slots_sold], total_figure=$_POST[total_figure], apps_sat=$_POST[apps_sat]");


mysql_close($con);
?>

问题是该表正在更新某些时间,有时则不是,任何人都有任何想法的原因?这真的很简单,我认为它只是一种魅力。

2 个答案:

答案 0 :(得分:2)

您没有验证通过的任何数据。另外,我建议将MySQLi用于预处理语句,以使事情更安全一些。

// create a new MySQLi object
$mysqli = new mysqli('host', 'user', 'password', 'database');

// create var for each POST array item you need
$slots_sold   = $_POST['slots_sold'];
$total_figure = $_POST['total_figure'];
$apps_sat     = $_POST['apps_sat'];

//check to make sure each field is set
if(isset($slots_sold) && isset($total_figure) && isset($apps_sat))
{    
     // prepare mysqli statement for your data
     if($stmt->prepare("UPDATE stats SET `slots_sold` = ?, `total_figure` = ?, `apps_sat` = ?"))
     {  
         // bind each variable to query, respectively (? is place holder for var)
         // s = string ('sss' means three strings). i = integer if needed
         $stmt->bind_param('sss', $slots_sold, $total_figure, $apps_sat);
         $stmt->execute(); // execute your query
     }
     else
     {
         $stmt->error; // there was an error with the query, show the error
     }
}
else
{
     echo 'You did not fill out all of the fields.';
}

$stmt->close; // close mysqli connection

希望这会对你有所帮助。根据您传递的数据,我将使用preg_match检查每个数据。以下是一些非常简单的正则表达式,可以帮助您入门:

/[a-zA-Z ]+/     (Any letter, lowercase or uppercase including spaces atleast once)
/[a-zA-Z]+/      (Same as above, without spaces atleast once)
/[a-zA-Z0-9]+/   (Any letter, lowercase or uppercase including numbers atleast once)
/[0-9]+/         (Any number atleast once)

preg_match('/[a-zA-Z]+/', $str, $matches); // you can throw this in a for loop to check each var if they all require the same pattern

答案 1 :(得分:1)

试试这个:

$sold  = $_POST['slots_sold'];
$total = $_POST['total_figure'];
$app   = $_POST['apps_sat'];

mysql_query("UPDATE stats SET slots_sold='$sold', total_figure='$total', apps_sat='$app'");

我还建议您查看mysql PDO