0

I have written some code to access my database and echo the results onto the webpage. Unfortuantely, I must have something wrong in my code. Thank you so much for any assistance.

$conn = new mysqli("website.com","Ericjs","Password","i4706992_wp1");
if ($conn) {
echo "Connection established! <br>";
} else {
die("Connection failed. Reason: ".mysqli_connect_error());
}
echo "Eric, I'm here first <br>";
$sql="SELECT Facility Name, Address, City, State, Zip FROM 'wp_facilities' 
WHERE 'Zip' = '01040' LIMIT 50";
echo "Eric, I'm here second <br>";
$results=mysqli_query($conn,$sql);
echo "Eric, I'm here third <br>";
if (mysqli_num_rows($results)>0) {
while($row=mysqli_fetch_array($results))  {
echo "Let's get ready to roll! <br>"; 
echo $row[1]." ".$row[2]." ".$row[3]." ".$row[4]." ".$row[5];
echo "<br>";
}
}
mysqli_close($conn);

The output I get are the echoes prior to the if statement above.

Connection established!
Eric, I'm here first
Eric, I'm here second
Eric, I'm here third

I was looking for the results to be displayed as:

"Ryan Rink" "524 Pleasant St" "Watertown" "Massachusetts" "01040"

  • After your `if (mysqli_num_rows($results)>0) {` write another debug line, and see if it reaches there. If it doesn't then no results are being returned. – Airwavezx Oct 21 '18 at 09:26
  • The problem seems to be here, where you shouldn't wrap the *table and field names* in single quotes: `SELECT Facility Name, Address, City, State, Zip FROM 'wp_facilities' WHERE 'Zip' = '01040' LIMIT 50`. The `Facility Name` is also not **escaped**. Check the answers [here](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-back-ticks-in-mysql) for more details on using single/double quotes and back ticks in SQL queries. – Sally CJ Oct 21 '18 at 10:12
  • What is the difference between these two connect codes? $conn = mysqli_connect("Website","Ericjs61","Password","i4706992_wp1"); and $conn = new mysqli("Website","Ericjs61","Password","i4706992_wp1"); – Eric J Simmons Oct 21 '18 at 20:15
  • @EricJSimmons The difference is `mysqli_connect()` is a procedural way, whereas `new mysqli()` is an OOP way. See the PHP [manual](http://php.net/manual/en/function.mysqli-connect) for more details. – Sally CJ Oct 22 '18 at 03:34

1 Answers1

0

I would comment, but don't have enough reputation. There are two problems.

  1. There are no results returned because your query is incorrect. As Sally CJ pointed out.
  2. Array indexing begins at 0, but you attempting to print results starting from index 1. This will result in an undefined offset error.
BambiOurLord
  • 372
  • 5
  • 12