Ben
Ben

Reputation: 3

PHP integer variable in mySQL query

I'm trying to input a PHP variable (in this case $beg) into a mySQL query but it returns an empty array result. The type of the field in the database is an integer. When I type in an actual value instead of the variable I get the correct result. What's wrong?

    $beg = time()-5000;
    settype($beg, "integer");

    $result = mysql_query('SELECT * FROM records WHERE time>=$beg ORDER BY time ASC');

    $statusdata = array();
    while ($row = mysql_fetch_array($result)) {
    array_push($statusdata, $row["status"]);
    }

Upvotes: 0

Views: 5567

Answers (5)

Pipala
Pipala

Reputation: 197

You should use prepared statements instead of mysql_query.

$beg = time()-5000;
settype($beg, "integer");

$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT status FROM records WHERE time>=? ORDER BY time ASC");
$stmt->bind_param('i', $beg);
$stmt->execute();

$stmt->store_result();
$stmt->bind_result($status);

$statusdata = array();
while($stmt->fetch())
{
  array_push($statusdata, $status);
}

$stmt->close();

Upvotes: 2

c42759
c42759

Reputation: 19

try this method, I use a lot:

$beg = time() - 5000;
$query = sprintf("SELECT * FROM %s WHERE time >= '%o' ORDER BY %s ASC", "records", $beg, "time");
$result = mysql_query($query);

remeber, time() result is Integer, you don't need set him in to an Integer

Upvotes: 0

Purushottam zende
Purushottam zende

Reputation: 552

Change your query

$result = mysql_query(" SELECT * FROM records WHERE time >= $beg ORDER BY time ASC ");

You cannot use variable inside single quotes.

Upvotes: 0

Ivan Cachicatari
Ivan Cachicatari

Reputation: 4284

Change the line

$result = mysql_query("SELECT * FROM records WHERE time>=$beg ORDER BY time ASC");

You must use double quote strings to put variables.

Upvotes: 0

Dylan
Dylan

Reputation: 1402

Make sure you use double quotes when using $variables inside the string.

    $result = mysql_query("SELECT * FROM records WHERE time>= $beg ORDER BY time ASC");

Upvotes: 5

Related Questions