php - Function with string parameter

147

I have function

function count_where($param, $value)
{
    $result=mysql_query("SELECT COUNT(*) AS TOTAL FROM vote WHERE '$param'='$value'");
    $data=mysql_fetch_assoc($result);
    return $data['TOTAL'];
}

and try to call it

count_where('picture','black circle')

where picture has varchar type (in MySQL). It doesn't work.

This

$result=mysql_query("SELECT COUNT(*) AS TOTAL FROM vote WHERE picture='black circle'");
 $data=mysql_fetch_assoc($result);
 echo $data['TOTAL'];

work;

953

Answer

Solution:

if you want to encapsulate the column name, use backticks` instead of apostrophes'

But be careful, watch out for sql injection. Before running the query you can better do:

$param = mysql_real_escape_string($param);
$value = mysql_real_escape_string($value);
63

Answer

Solution:

replace single quotes in column name with backticks like this:

function count_where($param, $value)
{
    $result=mysql_query("SELECT COUNT(*) AS TOTAL FROM vote WHERE `$param`='$value'");
    $data=mysql_fetch_assoc($result);
    return $data['total'];
}
819

Answer

Solution:

$result=mysql_query("SELECT COUNT(*) AS TOTAL FROM vote WHERE ".$param."='".$value."'");

I think this will give you the answer

People are also looking for solutions to the problem: php - Pagination inside foreach loop

Source

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.