【发布时间】:2013-11-14 16:07:32
【问题描述】:
我使用字符串构建了一个“INSERT INTO”MySQL 查询,但这个查询只更新了“date”列并返回“0”作为“id”列的值
$c= "2013-11-29 12:00:00";//whole code
$d= "2013-11-30 12:00:00";
$date_3 = date("Y-m-d g:i:s", strtotime("$c"));
$date_4 = date("Y-m-d g:i:s", strtotime("$d"));
$results = array($date_1);
$i = $date_3;
$allCane="";
while ($i <= $date_4) {
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "\n";
$chunks = str_split($k, 19);
$nexstring = join('\')', $chunks);
$cane = implode(', (\'{$id}\', \'', str_split($nexstring, 21));
$allCane .= $cane; // appends $cane to $allCane
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}
$string ='(\'{$id}\', \' '.$allCane;
$string=substr($string,0,-12);
echo $string;//('{$id}', ' 2013-11-29 12:00:00'), ('{$id}', ' 2013-11-30 12:00:00')
$id=54;
$insert = mysql_query("INSERT INTO events (id, date) VALUES $string");
// i build the query using $string.
$insert 的语法是正确的,但实际上我无法更新“id”列。
有什么方法可以使 $id 进入字符串?
【问题讨论】:
-
请不要再使用
mysql_*函数,它们已被弃用。有关详细信息,请参阅Why shouldn't I use mysql_* functions in PHP?。相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is a good tutorial. -
你是如何创建你的
$string的? -
在这种情况下,只需将 SQL 写入变量,而不是直接写入 mysql 命令。这样您就可以输出生成的查询并对其进行调试。调试就是一切!
-
您的
$string中似乎包含文字字符串'$id'。这不会被$id变量神奇地替换。你需要设置$id之前你设置$string然后添加$id到它。 -
或者需要使用
str_replace将'$id'替换为$id的值。