2013-01-06 58 views
1

该程序需要一个用户的变量$ ask,这是一个感兴趣的类别,例如体育,电影等。然后检查数据库是否存在该类别,如果该类别不存在,则添加它到数据库。数据库内存,表 - '兴趣类别',目前只有3列IID,类别和评论。但是添加到数据库中运行,如果它是在数据库中,打印出的是在那里不起作用....php - 无法获得查询的输出结果。 (如果有输出的话)

问题主要在于这些行:

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); 

    ?> 
+0

尝试启用误差汇报 “的error_reporting(E_ALL);” –

+0

哪一行是我在开始时添加的?我已经将问题缩小到这个部分/ *获取关联数组*/ \t printf('here1'); ($ row = mysqli_fetch_assoc($ result)){ printf('here2'); },因为'here1'被打印,但不是'here2' –

+0

error_reporting(E_ALL);添加在顶部,它会显示,如果有任何错误.. –

回答

0

变化:

if ($result = mysqli_query($link, $query)) 
{ 
    if (($row = mysqli_fetch_assoc($result)) === null) 
    { 
     notAnInterest($ask, $link); 
    } 

    /* fetch associative array */ 
    while ($row = mysqli_fetch_assoc($result)) 
    { 
     printf ("%s (%s)\n", $row['Category'], $row['Comment']); 
    } 

    /* free result set */ 
    mysqli_free_result($result); 
} 

要:

if ($result = mysqli_query($link, $query)) 
{ 
    if (0 == mysqli_num_rows($result)) 
    { 
     notAnInterest($ask, $link); 
    } 
    else 
    { 
     /* fetch associative array */ 
     while ($row = mysqli_fetch_assoc($result)) 
     { 
      printf ("%s (%s)\n", $row['Category'], $row['Comment']); 
     } 
    } 

    /* free result set */ 
    mysqli_free_result($result); 
} 
+0

不确定我是否看到你的观点,因为notAnInterest($ ask,$ link)仅在$ row = mysqli_fetch_assoc($ result))=== null时才运行。 –

+0

@LindsayW,运行上面的代码并告诉我你输出的浏览器的输出,你应该得到字母。将帮助我们看到它失败的地方。 –

+0

动物(不在数据库中)获得:cdea 调试:插入到'interestcategories'('Category','Comment') VALUES('animals','用户添加') added animalsg运动是在数据库中获取:cdg –