Converting from mysql to mysqli (mysql_fetch_array

2019-03-31 14:11发布

问题:

I have some php code that was like this:

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

I'm now trying to convert it to mysqli_fetch_array as shown here http://php.net/manual/en/mysqli-result.fetch-array.php (Example #1 Object oriented style)

I'm not sure what the example means by "$result".

This is what I've converted my code to so far:

<?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'"));
?>

There is probably a lot wrong with as I am learning mysqli, but right now it errors on

Fatal error: Call to a member function fetch_array()

回答1:

UPDATE queries do not return result objects, it returns TRUE (assuming success). You're then trying to call TRUE->fetch_array(), which obviously won't work.

Now, for doing what you actually want to do, try this:

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


回答2:

Looks like you are trying to use an old result object (result of your UPDATE) to get results for a new query. You need to run the new query first, assign its result to an object, and then fetch the results from object. Check out the last three lines of your script re-written:

$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();
?>

Here is a helpful page with other result object methods: http://www.php.net/manual/en/class.mysqli-result.php