Jump to content

Variable in MySQL query


mcfmullen

Recommended Posts

Hello,

 

I am trying to pass a php variable into a MySQL select query and am not having any success. Here's my code:

<?php
$columns = 5;

$result = mysql_query("SELECT * FROM Animals WHERE Animals.introDateAnimal = '2010-06-03'");
$url='http://www.cool.com/animalpic/';

$numofrows = mysql_num_rows($result);
echo "<table>";

for($i = 0; $i < $numofrows; $i++) {
    $row = mysql_fetch_array($result);
    if($i % $columns == 0) {
        echo "<tr>";
    }
    echo "<td><img src='".$url.$row['photoAnimal']."' height='100px' width='100px'>";
    echo "<br>";
    echo "<a href='http://www.cool.com/animals.php?animal={$row['nameAnimal']}'>{$row['nameAnimal']}</a></td>";
    if(($i % $columns) == ($columns - 1) || ($i + 1) == $numofrows) {
        echo "</tr>";
    }
}
echo "</table>";
?>

 

The code above gives me no results. No errors, but no results either. If I hard code the variable as such:

<?php
$columns = 5;
$date = 2010-06-03;

$result = mysql_query("SELECT * FROM Animals WHERE Animals.introDateAnimal = '$date'");
$url='http://www.cool.com/animalpic/';

$numofrows = mysql_num_rows($result);
echo "<table>";

for($i = 0; $i < $numofrows; $i++) {
    $row = mysql_fetch_array($result);
    if($i % $columns == 0) {
        echo "<tr>";
    }
    echo "<td><img src='".$url.$row['photoAnimal']."' height='100px' width='100px'>";
    echo "<br>";
    echo "<a href='http://www.cool.com/animals.php?animal={$row['nameAnimal']}'>{$row['nameAnimal']}</a></td>";
    if(($i % $columns) == ($columns - 1) || ($i + 1) == $numofrows) {
        echo "</tr>";
    }
}
echo "</table>";
?>

 

I get the output that I want. So the question is, how do I get the variable (first code) to work?

Link to comment
https://forums.phpfreaks.com/topic/203972-variable-in-mysql-query/
Share on other sites

$date = 2010-06-03; is a mathematical expression and results in the number 2001 (2010 minus 6 minus 3.)

 

Use the following to assign the string consisting of the characters '2010-06-03' that represents a date value -

$date = '2010-06-03';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.