Going through a PHP MySQL tutorial and switching the PHP out for PDO; at any rate, my query is coming up blank.
$get_cat = $that->dbh->query("SELECT `cat_name`, `cat_desc` FROM `categories`");
if(isset($get_cat))
{
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
{
printf("
<tr>
<td>".$row['cat_name']." : ".$row['cat_desc']."</td>
</tr>
");
}
}
else
{
echo '<tr><td>return is false</td></tr>';
}
$That refers to:
include('db.php');
$that = new lib();
OLD:
So, why is my query blank? Before putting the die in it would return Boolean and give in an error in the loop with the die in it just comes up blank. The categories table has data in it and the page is refreshed on submission for new entries.
NEW:
Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\forum\create_category.php on line 36
Line 36 is the while loop line.
mysql_fetch_array is not PDO. You would need something like:
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
To get your rows.
Nor can you use mysql_error() to get the error. You could use for example $that->dbh->errorInfo() but you should look into exceptions for a more robust way to catch all errors.
Edit: You should check what the error is. Using isset is pointless as you have just assigned a value to it, so it will always be set.
You need to tell PDO to throw errors.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res = $that->dbh->query("SELECT cat_name, cat_desc FROM categories");
while($row = $res->fetch())
{
echo "<tr><td>$row[cat_name] : $row[cat_desc]</td></tr>\n";
}
run your code, read the error message and take appropriate action
Don't forget to add the first line into your db.php file, to make the setting permanent
Your query is incorrect -- is this what you're trying to do?
SELECT `categories`.`cat_name`, `categories`.`cat_desc` FROM `categories`
Hard to know without seeing you table structure.
Related
I got php fatal error after transfer server with php v5.6.19, before that I had no problem at all with following script
Fetch data from db table:
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
Populate data in HTML:
<ul class="department overflow-scroll text-center">
<?php
$shop = new Shop;
$depts = $shop->get_department_list($mysqli);
while($dept = $depts->fetch_object()){
echo '<li>'.$dept->dept_name.'</li>';
}
?>
</ul>
In the end I got an error:
Fatal error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\project\include\header.php on line 206
First, you are returning a boolean from your function. So, no wonder PHP says you so.
Second, you should keep the matters separated. a function that works with mysqli should keep all mysqli stuff inside. An return just an array, that can be used anywhere without the need to call mysqli functions again.
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
return $sql->fetch_all();
}
And then use not while but foreach
foreach ($depts as $dept) ...
Besides (and more for the people who may chance to land on this question looking for an answer to their question) you should always set proper error reporting for mysqli, like it shown in this answer
Update your while loop for that case when you get false from $shop->get_department_list() call
updated while like this check for $depts if any data then get $dept:
while($depts && $dept = $depts->fetch_object()){
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.
I'm trying to implement pagination using PHP. I found that calling exec to the connected database prevents the further query calls from working.
The piece of code at hand:
<?php
// Pagination logic
//Here we count the number of results
$query = "SELECT COUNT(*) as num FROM gig";
$total_pages = $db->exec($query);
$total_pages = $total_pages[num];
?>
After it if I try to use a query such as:
<?php>
foreach ($db->query("SELECT sname, start, venue FROM gig WHERE start = '0000-00-00 00:00:00'") as $a) {
$row="<tr><td>$a[sname]</td><td>To be announced</td><td>$a[venue]</td></tr>\n";
print $row;
}
?>
it returns
Warning: Invalid argument supplied for foreach()
As soon as the first code block is removed, the query works fine. When I check the value of $total_pages, it's 0, so something must be going wrong along the way. As far as I know, I use it in the same way as the query(which works on its own), so is there any reason why it doesn't work?
The PDO is initialized in the following way:
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_server", $db_user, $db_pw);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
session_start();
From Manual
PDO::exec() does not return results from a SELECT statement. For a
SELECT statement that you only need to issue once during your program,
consider issuing PDO::query(). For a statement that you need to issue
multiple times, prepare a PDOStatement object with PDO::prepare() and
issue the statement with PDOStatement::execute().
Used a function of the STATEMENT object had after using querying to count the rows instead of exec:
$dbq = $db->query("SELECT * FROM gig");
$rows = $dbq->rowCount();
About the latter code block not working because of the exec failing - it seems to just be the way php queries work, if one fails, all fail. The foreach() error is for the object it's provided is not an array, for it failed.
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.
I'm trying to get a list from my MySQL database, which normally works fine. But today I'm getting this error Fatal error: Call to a member function setFetchMode() on a non-object in "Way too long path to file here".
This is my PHP code:
$conn = new PDO('mysql:host=localhost;port=3306;name=erty', 'erty', 'Ops, that my password ...');
$result = $conn->query("SELECT name FROM mod_devs");
$result->setFetchMode();
foreach ($result as $row) {
echo '<tr><td>'.$row['name'].'</td></tr>';
}
Now, you probably understand my goal :)
Generally Call to a member function setFetchMode() on a non-object means that $result is not available. Probably because of MySQL error - either in connection or query. Check if($conn) or if($result).
You still need to fetch the result...
So instead of foreach....do while...
while ($row = $result->fetch()) {
//your code here
}
you maybe need prepare not query
$result = $conn->prepare("SELECT name FROM mod_devs");
or this
$result->setFetchMode(PDO::FETCH_OBJ);
I just found the error. In the connection I wrote name=erty not dbname=erty!
Sorry for taking up your time :(