从mysql转换为mysqli(mysql_fetch_array)

时间:2012-05-09 14:23:26

标签: php mysql oop mysqli

我有一些像这样的PHP代码:

$row = mysql_fetch_array ( mysql_query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'")); 

我现在正尝试将其转换为mysqli_fetch_array,如此处所示http://php.net/manual/en/mysqli-result.fetch-array.php(示例#1面向对象的样式)

我不确定这个例子的意思是" $ result"。

这是我到目前为止转换代码的原因:

<?php 
include('../config.php'); 
if (isset($_GET['uid']) ) { 
$uid = $_GET['uid'];
$id = $_GET['id'];  
if (isset($_POST['submitted'])) { 
foreach($_POST AS $key => $value) { $_POST[$key] = mysqli_real_escape_string($value); } 

//Query for tblFacilityHrs
$sql = " UPDATE tblFacilityHrs SET `title`='{$_POST['title']}',`description`='{$_POST['description']}' WHERE `uid` = '$uid' "; 
$result = $mysqli->query($sql) or die($mysqli->error);

//Query for tblFacilityHrsDateTimes
$sql2 = "UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`days`='{$_POST['days']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; print $sql2;
$result2 = $mysqli->query($sql2) or die($mysqli->error);

echo ($mysqli->affected_rows) ? "Edited row.<br />" : "Nothing changed. <br />"; 
echo "<a href='list.php'>Back</a>";
} 
$row = $result->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
$row2 = $result2->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'"));
?>

因为我正在学习mysqli,所以可能有很多错误,但现在它在

上出错了
  

致命错误:调用成员函数fetch_array()

2 个答案:

答案 0 :(得分:4)

UPDATE查询不返回结果对象,它返回TRUE(假设成功)。您接着尝试拨打TRUE->fetch_array(),这显然无效。

现在,为了做你真正想做的事,试试这个:

$row = $mysqli->query("SELECT.....")->fetch_array();

答案 1 :(得分:1)

看起来您正在尝试使用旧的结果对象(UPDATE的结果)来获取新查询的结果。您需要先运行新查询,将其结果分配给对象,然后从对象中获取结果。查看重写脚本的最后三行:

$facilityHoursQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'");
$facilityHoursDateTimesQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'");

$facilityHoursRow = $facilityHoursQueryResult == FALSE ? NULL : $facilityHoursQueryResult->fetch_array();
$facilityDateTimesRow = $facilityHoursDateTimesQueryResult == FALSE ? NULL : $facilityHoursDateTimesQueryResult->fetch_array();
?>

这是一个包含其他结果对象方法的有用页面: http://www.php.net/manual/en/class.mysqli-result.php