Why is my PHP code returning an empty array?

<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
@mysql_select_db("trynew") or die(mysql_error());
if (isset($_POST["data_found"])) {
$user = $_POST['data_found'];
}
echo $user;
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);
echo $jsondata;
mysql_close();
?>

In the above code I am trying to return the data based on the name that the user gives , I do get the output but it’s an empty object but if I hardcore the user value to be selected in the PHP itself then it shows proper object. What am I doing wrong , as I am new to PHP I am not able to get it.
when I am hard coding like :

$user = "mon" $query = "SELECT * FROM trynewtable where name = '$user' ";

So I guess it’s not able to get the value from $_POST[‘data_found’] here’s my js code :

var loadingFunc=function()
{
 var xhr;

 if(window.XMLHttpRequest)
{ 
 xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
    if(xhr.success =200)
    {
        jsonData = xhr.responseText;
        document.getElementById("dvID").innerHTML = jsonData;
        console.log(typeof jsonData);
        var parsejson = JSON.parse(jsonData);
        console.log(typeof parsejson);
        console.log(parsejson);
        document.getElementById("dvIDO").innerHTML = parsejson[0].Age;
    }
    else
    {
        document.getElementIdById("dvID").innerHTML = "it's not success ";
    }
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};
window.onload = loadingFunc();

To get the code formatting to work, you can either highlight it and click on the </> icon on the editor toolbar, or use three backticks ( ``` ) on the line before and the line after your code.

Always:

  1. set error_reporitng(-1); and ini_set(‘display_errors’, ‘true’);
  2. test returned function variables
  3. use mysqli or PDO because mysql has been deprecated

This works on my localhost, try :

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

$dbhost     = dbSERVER;
$username   = dbUSER;
$password   = dbPWORD;
$connection = mysqli_connect('localhost',$username,$password);
mysqli_select_db($connection, dbDBASE) or die(mysqli_error());

// MAYBE USER
    $user = 'Yes we have no user???';
    if (isset($POST["datafound"])) {
        $user = $POST['datafound'];
    }
    echo $user;

// QUERY RESULTS
   $query      = "SELECT * FROM sensedata where id <= 8 ";
   $all_result = array();
   $result     = mysqli_query($connection, $query);
   if($result===FALSE)
   {
      die(mysqli_error());
   }else{
      // DISPLAY RESULTS
         while($row = mysqli_fetch_assoc($result))
         {
            $all_result[] = $row;
         }
        echo '<pre>';
          print_r($all_result);    
        echo '</pre>';
    }
mysqli_close($connection);

if(false){
    header('Content-Type: application/json');
    $jsondata = json_encode($all_result);
    echo $jsondata;
}    


1 Like

Hi John,
Thanks for the reply, I will follow your suggestions but what I want is to select the data based on the user input(the name that user gives), but here you are retrieving all the data that whose id <=8 it works like that as I have mentioned in my post like if I put the query like : ```

SELECT * FROM trynewtable where name =" mon "

Try creating this function at the top of your page and test the variables that are not working:

function fred( $val )
{
   echo ''<pre>;
      print_r( $val );
   echo ''</pre>;

// example
fred( $sql );  die; // 

if you have PhpMyAdmin loaded then copy and paste fred() results into PhpMyAdmin to test the query.

I notice in you example there is a space. Try using the following:

 $user = trim( $user );
 $sql = 'SELECT * FROM trynewtable where name="' .$user .'"' 
fred( $sql );

**Edit:**
In function  fred(...) you could replace `print_r( $val );` with `var_dump( $val );`


Thanks John , now I am not in front of my system , i will try it later and let you know…

1 Like

mysq

1 Like

it is no longer deprecated because it ceased to exist in December 2015.

things are only deprecated between when their future removal is announced and when that actual removal takes place. The period something is deprecated allows time for the code to be rewritten to stop using the deprecated code before it gets removed.

In this case mysql was deprecated in July 2013 which gave everyone still using it then 18 months to convert it to one of the two replacements that were introduced in July 2004.

1 Like

Hi The problem was in javascript and not in PHP I was getting the value of the textbox before clicking the button , so it was sending null value to $_POST

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.