2

I'm learning php and right now I'm figuring out dbs. Was following up with a tutorial on YT and got stuck in the following:

"retrieve all records from table"

Specifically, I can connect to my DB no prob, but when I perform the select query it prints nothing

Here's my code...

<?php

	//error_reporting(0);
	
	require 'connect.php';
	
	$result = $db->query("SELECT * FROM sample-objects");
	
	//$result = mysqli_query($db, "SELECT * FROM sample-objects");
	
	print_r($result);	
	

?>

and my connection script

<?php

	$db = new mysqli('localhost','root','','test');
	
	// echo $db->connect_errno,"\n";
	
	if ($db->connect_errno)
	{
		echo "error: ",$db->connect_error; /* Imprime descripción de error de DB */
		//die("Site offline");
	}

?>

I don't get any errors from "connect.php" and I do have 2 records in my db (did so from phpmyadmin)

Any help would be appreciated, thanks :)

1 Answer 1

1

Having checked for errors on your query would have signaled the error in your table name containing a hyphen:

SELECT * FROM sample-objects
                    ^ that is the problem character

where MySQL is interpreting that as sample MINUS objects thinking you want to do math here.

Either you wrap it with ticks (careful, those are not single quotes ') copy/paste as shown:

SELECT * FROM `sample-objects`

or rename it with an underscore (rename your table first before using this example)

SELECT * FROM sample_objects

References:


Example from the manual on mysqli_query():

if (!$mysqli->query("SET @a:='this will not work'")) {
    printf("Error: %s\n", $mysqli->error);
}

I also noticed you commented out //error_reporting(0);

That actually turns error reporting off. You need to turn it on and to display:

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That got me unstuck :) I had checked in myphpadmin and it showed the select query without any problems, eclipse didn't highlight the error so I thought I was safe. I'll be more careful now, just getting the hang of it. Once again, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.