This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
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()
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();
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
Related
This question already has answers here:
ErrorException : implode(): Passing glue string after array is deprecated. Swap the parameters
(6 answers)
Closed 4 months ago.
Please help,
i got error "Warning: join(): Invalid arguments passed in ... on line...".
Here is my code:
$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC";
$stmt = $DB_con->prepare($query);
$stmt->execute();
$kategori = array();
if($stmt->rowCount()>0) {
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$kategori = print($row['kategori']);
}
}else{
echo "Nothing here...";
}
join($kategori, ',');
I expect the output : Data,Data,Data,Data,Book,Book
but the actual output is "DataDataDataDataBookBook" anda error "Warning: join(): Invalid arguments passed in ... on line..."
Just append $row['kategori'] in each iteration and change the order of parameteres in join() or implode() call:
<?php
// Get data
$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC";
$stmt = $DB_con->prepare($query);
$stmt->execute();
// Fetch data
$kategori = array();
if ($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$kategori[] = $row['kategori'];
}
} else {
echo "Nothing here...";
}
// Output
echo implode(',', $kategori);
?>
An alternative to fetching a bunch of records and then joining them together would be to use GROUP_CONCAT() in mysql to do the work for you. Also as you are not binding anything - you can just call query(). Then you will have 1 row from the database with the content - so the last bit is to say if it's empty, then set the value to Nothing here... (done using ?:)
...
$query = "SELECT GROUP_CONCAT(`kategori`) as kategori
FROM `table`
ORDER BY `id` DESC";
$stmt = $DB_con->query($query);
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$output = $row['kategori']?:"Nothing here...";
echo $output;
If you still need the individual data rows, then another alternative is to use PDO::FETCH_COLUMN and fetchAll() to return the results, then implode() as in the other solution...
$query = "SELECT `kategori`
FROM `table`
ORDER BY `id` DESC";
$stmt = $DB_con->query($query);
$kategori=$stmt->fetchAll(PDO::FETCH_COLUMN);
echo implode(',', $kategori)?:"Nothing here...";
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
I'm running PHP 7.0 and connected to a mysql db with a record matching the query in the below:
$query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($query);
print_r($row[0]);
Print outputs 1, as expected as there is only one record matching that username.
However, the following function returns false
function user_exists(){
$exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($exists_query);
return ($row[0] == 1) ? True : False;
}
But I would expect it to be true. Am I misusing the fetch function?
What exactly does your first print_r statement output?
It should print an array, not an integer.
Your $row is an array of arrays.
So $row[0] will not be '1' but something like array('1').
I think it's because the $conn is not accessible. Try this
function user_exists(){
global $conn;
$exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($exists_query);
return ($row[0] == 1) ? True : False;
}
Edit:
As mentioned by #trs, you should consider your $row[0] output.
I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");
I am trying to write PHP code to update a value once it exist, and if it doesn't then insert it. Part of this function works which is the insert part however the update doesn't seem to work my code is below:
<?php
$id = $_GET['Track'];
$user = $_GET['User'];
$rating = $_GET['Rating'];
include("connect.php");
$query = "UPDATE `rating` SET `rating` = '$rating' WHERE track_id = '$id' AND user_id = '$user' AND rating_set=NOW()";
$sth = $dbc->query($query);
$rows = $sth->rowCount();
if ($rows == 0) {
$query = "INSERT INTO rating values ('$id','$rating','$user',NOW())";
$results = $dbc->query($query);
$rows = $results->rowCount();
}
/* output in necessary format */
header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";
$dbc = null;
?>
Your update query can't work.
You are only updating data where rating_set is exactly NOW(). That will most likely not fit on any data record. You probably only want to use the date part.
you are using NOW() in update query, which gives current time. Which will never be same!!! try removing '....AND rating_set=NOW()' from your update query.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();