Monday 27 June 2016

fetch_assoc error with sql query in php





I get this error :




Call to a member function fetch_assoc() on a non-object




when I use this code :



$sql = ('select '.$metric1.' as t1metric from '.$table1.' t1 WHERE '.$date1.' between ('.$start_date.' AND '.$end_date.')');



but it works when I use this :



$sql = ("select t1.clicks as t1clicks from aaa t1 WHERE t1.date between ('2015-11-11 and '2015-11-10')");


I first thought it was an issue with the different quotation marks " and ' but I was proven wrong.



This is my full code :




$servername = 'XXXXX';
$username = 'XXXXX';
$password = 'XXXXX';
$dbname = 'XXXXX';
$table1 = 'aaa';
$table2 = 'bbb';
$metric1 = 'clicks';
$metric2 = 'clicks';
$date1 = 'date';
$date2 = 'date';

$start_date = '2015-11-10';
$end_date = '2015-11-11';

$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);

// Creation of SQL query
$sql = ("select t1.date, t1.clicks as t1clicks , t2.clicks as t2clicks from aaa t1, bbb t2 WHERE t1.date = t2.date AND t1.clicks != t2.clicks group by date");


// Run the query
$query = $Db->query($sql);

//
while ($row = $query->fetch_assoc())
{
echo sprintf("date: %s, aaa: %s, bbb: %s \n", $row['date'], $row['t1clicks'], $row['t2clicks']);
}

Answer




The reason you are getting the error is because you have not wrapped the dates with quotes.



WHERE '.$date1.' between ("'.$start_date.'" AND "'.$end_date.'")');
will work.



Hope this helps!



Cheers!


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...