MySQL function not working [closed]

2020-01-19 00:54发布

When I do

SELECT count(*) FROM table_name WHERE id= 2

The code works but when I write it like this:

$try= 2;
SELECT count(*) FROM table_name WHERE id= $try; 

The code doesn't work anymore. Can someone please explain?

标签: php mysql
3条回答
女痞
2楼-- · 2020-01-19 01:33

MySQL use @ symbol for the variables.

Read http://dev.mysql.com/doc/refman/5.0/en/user-variables.html for more information

Try this would work:

SET @try='test';
SELECT count(*) FROM tble_name WHERE id = @try;
查看更多
Bombasti
3楼-- · 2020-01-19 01:38

use this

$try= 2;
$sql=sprintf("SELECT count(*) FROM table_name WHERE id=%d",$try); 
查看更多
趁早两清
4楼-- · 2020-01-19 01:46

First of all you have to "include" your parameter properly into string

'SELECT count(*) FROM tble_name WHERE id='.$try; 

Second, you have to pass it to mysqli object

$result = $mysqli->query('SELECT count(*) FROM tble_name WHERE id='.$try);

Then you have to fetch result

while ($row = $result->fetch_row()) {
        /* your logic here */
    }

Obviously you have to create new mysqli object properly, as explained into link that I've provided you.

查看更多
登录 后发表回答