该程序从用户那里获取一个变量$ask,该变量是一个感兴趣的类别,例如运动、电影等。然后检查数据库是否存在该类别,如果不存在则将其添加到数据库中。数据库内存,表 - “interestcategories”,目前只有 3 列 IID、Category 和 Comment。添加到数据库是可行的,但是如果它在数据库中,则打印出其中的内容是行不通的......
问题主要在于以下几行:
while ($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n", $row["Category"], $row["Comment"]);
}
/* free result set */
mysqli_free_result($result);
由于没有任何内容出现在屏幕上,甚至没有错误消息。应该只打印一行,因为该类别在表格中只出现一次。有任何想法吗?
<?php
error_reporting(E_ALL);
$link = mysqli_connect("localhost", "root", "", "memory");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
function notAnInterest($ask, $link)
{
$query2 = "INSERT into interestcategories (Category, Comment)
VALUES ('$ask', 'Added by user') ";
$result2 = mysqli_query($link, $query2);
echo "<pre>Debug: $query2</pre>\n";
if ( false===$result2 ) {
printf("error: %s\n", mysqli_error($link));
}
echo 'added ' . $ask;
}
if(isset($_POST['ask']) === true && empty($_POST['ask']) === false) {
$ask = trim($_POST['ask']);
$query = "
SELECT *
FROM `interestcategories`
WHERE `interestcategories`.`Category` = '$ask' ";
if ($result = mysqli_query($link, $query)) {
if(($row = mysqli_fetch_assoc($result)) === null) {
notAnInterest($ask, $link);
}
/* fetch associative array */
printf('here1');
while ($row = mysqli_fetch_assoc($result)) {
printf('here2');
//printf ("%s (%s)\n", $row["Category"], $row["Comment"]);
}
/* free result set */
mysqli_free_result($result);
}
}
/* close connection */
mysqli_close($link);
?>