Sulexk
Sulexk

Reputation: 61

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

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

Upvotes: 3

Views: 409

Answers (2)

John Woo
John Woo

Reputation: 263723

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,

Upvotes: 2

Sammitch
Sammitch

Reputation: 32242

  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.

Upvotes: 2

Related Questions