Daniel Cory Daniel Cory - 3 months ago 8
MySQL Question

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.

I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.

$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");


I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.

Answer

Actually mysqli_query() requires two parameters... check the following sample example ..

<?php
$conn = mysqli_connect('localhost','root','','your_test_db');

$_GET['page'] = 1;

$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);


echo ("You have just entered in " . $data['id'] . "!!! YAY");

?>

As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...

Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.

Also, you can always check whether your database is connected or not. So that you have a better idea.

// Check connection
if (mysqli_connect_errno())
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..

Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.