php - My code does not read from mysql database


I've tried to debug this times without success. Here is what I've tried so far

$cid= (string)$_GET['cid'];//I passed this from another page using get method
echo $cid; //My code works up to this point
$record = mysql_query("select * from questions where QType = '$cid'");
$array = array();
while($row = mysql_fetch_assoc($record))
            $array[] = $row;
    for($var = 0; $var<count($array);$var++)
        echo $array[$var]['Question'].'<br>';




This code will work and is a bit safer

//Connection part
$servername = "server_adress"; //It can be localhost or or some other IP
$username = "XXXXXX"; //Username for DB
$password = "YYYYYY"; //Password for that user
$database = "ZZZZZZ"; //DB name you are connecting to

//Create a new connection
$conn_to_db = new mysqli($servername, $username, $password,$database);

// Check connection
if ($conn_to_db -> connect_error) {
    die("Connection failed: " . $conn_to_db ->connect_error);

//Finished connection part

$cid = mysqli_real_escape_string($conn_to_db, $_GET['cid']); //Escapes special characters in a string for use in an SQL statement

$array = array();

if($stmt = $conn_to_db -> ("SELECT * FROM questions WHERE QType = ?")) {
   $stmt -> bind_param("s", $cid);
   $stmt -> execute();
   $stmt -> bind_result($question_from_db);  //Here you can put all variables you are fetching from DB
   while($stmt -> fetch()){
     //Iterate over rows - put your code here to fetch everything you need from DB and put in array
     $array[] = array('question' => $question_from_db);
   $stmt -> close();

//you can iterate over rows like this
foreach($array as $key => $value) {
 echo $value['question'];

Couple of things to keep in mind:

  • it's a good practice to avoid * (selecting everything from DB) and put only columns you need from DB
  • use prepared statement which is a safer way and protects you from SQL injection
  • MySQL is depreciated so try to avoid it (use mysqli or PDO)
  • The code above you need to adjust to your needs! It will not work as copy/paste. Put your DB connection and select columns from DB you need and add variables which you fetch from DB
  • Keep in mind there are more ways to do this, and someone will probably give another solution.
  • if you are not on a production server, it's good to have some error reporting to see the errors that are happening

People are also looking for solutions to the problem: file get contents - Assign Image SRC in php


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.