Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

receiving undefined variable when attempting to use count(*) in php

Tags:

php

mysql

I want to show the number of sales/buys a sales person has done. I have a search box which when I type in their name it should bring back a number . So to count total buys I am using this code:

<?php

mysql_connect ("****", "****","****")  or die (mysql_error());
mysql_select_db ("*******");

 $term = $_POST['term'];


$sql = mysql_query("select count(*) from car_orders where side='buy' and sales_id like '%$term%'");


while ($row = mysql_fetch_array($sql)){
 echo 'owner_id: '.$row['sales_id'];
echo '<br/> side '.$row['side'];
echo '<br/><br/>';
 }
?>

I have tried finding out how to just get the count figure to show on the page and have failed. Please could somebody help

like image 475
Sulexk Avatar asked May 30 '26 09:05

Sulexk


2 Answers

you need to add ALIAS

select count(*) AS totalCOUNT from car_orders where ....

and you can now get the value using that

$row['totalCOUNT']

but seeing on your query, neither sales_id nor side were projected. The query below is only an assumption

select `sales_id`,`side`, count(*) AS totalCOUNT
from car_orders 
where side='buy' and 
      sales_id like '%$term%'
GROUP BY `sales_id`,`side`

and now you can fetch all values,

$row['sales_id']
$row['side']
$row['totalCOUNT']

and that query is vulnerable with SQL Injection. Please take time to read the article below how to protect from it,

  • How can I prevent SQL injection in PHP?
like image 150
John Woo Avatar answered May 31 '26 21:05

John Woo


  1. You're only selecting the COUNT(*) column and nothing else.
  2. You're not using mysql_fetch_assoc(), so it's not an associative array.
  3. The mysql_ functions are deprecated, use mysqli or PDO.
like image 20
Sammitch Avatar answered May 31 '26 22:05

Sammitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!