我真的很难理解这一点,但却惨败。我想做的是基于URL传递的URL参数构建MySQL查询。我正在尝试创建一个可重复使用的动态脚本,该脚本可以根据URL参数执行它需要执行的操作。
这就是我所想到的,它似乎做了它应该做的事情(没有错误或任何事情),但实际上没有任何东西被插入数据库中。我知道我在某个地方犯了一个愚蠢的错误(或者想错了什么),所以希望你们中的一个人能给我指明正确的方向。
谢谢!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
您错过了mysql_query($sql)
:
if(!mysql_query($sql)){
//die(mysql_error());
}
请考虑使用PDO或My SQLi使用参数化查询,因为mysl_*函数已折旧。
您的SQL完全错误。您对INSERT
使用field = value
语法,然后将数组连接起来,就好像它是字符串($fields)
一样,并且在值周围缺少了几个括号。
有几件事:我为php<->找到了当我陷入困境时,查看mysql中的内容并直接在phpmyadmin中体验这些查询是很重要的。
1-在我的代码中,当查询失败或设置了调试标志时,我会输出mysql_error()。这通常解释sql问题的方式可以指出拼写错误的字段名等…
2-通过这种方式,我可以将mysql查询直接输入phpmyadmin,并对其进行调整,直到它给出我想要的结果。(当我在那里的时候,我也可以使用explain来查看是否需要优化表格)
代码中的细节。与C语言不同,sprintf是隐含的。以下是我如何编写您的代码:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);