I have a page where I am using a parameter in the URL as a filter for my SQL query.
I created a variable from the URL parameter:
$station = htmlspecialchars($_GET["station"]);
Then set up a conditional query depending on whether or not the URL parameter is set:
if(isset($_GET['station'])) {
$query = "SELECT * FROM song_of_the_day WHERE station = '$station'";
}
else {
$query = "SELECT * FROM song_of_the_day WHERE end_date >= CURDATE()";
}
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
Then I display the results in a table:
echo "<table width='758' border='0' cellpadding='10' cellspacing='0' class='myTable'>";
while($row = mysql_fetch_array( $result )) {
echo '<tr>';
echo '<td align="left" width="48">' . $row['station'] . '</td>';
echo '<td align="left">' . date('M j, Y',strtotime($row['end_date'])) . '</td>';
echo '<td width="24" align="left"><img src="http://yourligas.yourli.com/ad-inventory/edit.png" border="0"></td>';
echo '<td width="24" align="left"></td>';
echo "</tr>";
echo '</tbody>';
}
echo "</table>";
The query works find when the ELSE command uses the query, where I'm not relying on the parameter in my SQL, but the problem I am seeing when the URL parameter ISSET is only one row gets displayed from the query when there is more than one row that matches the criteria in the actual database. Does anybody know why this is happening?
Thank you
In this line, you appear to be consuming the first row of data while attempting to get the number of rows found:
$num_rows = mysql_fetch_row($result);
This removes the first row from your result cursor.
Instead, you probably meant to do the following:
$num_rows = mysql_num_rows($result);
Related
I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}
I have a system which looks through a database, creates a table of a specified size and then fills the cells with either full or empty depending if there is data in the database for that specific location.
At the moment it works by doing a SQL query for each cell and then populating, but I have 30,000+ records in the database and even with a LIMIT 1 it's still taking about 5 second to load the table.
I'm wondering if dumping the entire contents into a PHP array and then querying that way would be better, but can't work out the best way to sort it, any tips welcome.
Current (working) code:
echo <<<EOD
<table class="racktable"><tr>
<td colspan ="$colspan">Rack Details </td>
</tr>
<tr>
<td colspan ="$colspan"><center>Edit Rack / Empty Rack / Delete Rack</center> </td>
</tr>
EOD;
//Loop through rows, creating a <tr> for each in the table
for ($row1 = 1; $row1 <= $rows; $row1++) {
echo <<<EOD
<tr><td><a name="$row1"></a>$row1</td>
EOD;
//Loop through columns creating <td> within <tr>
for ($col1 = 1; $col1 <= $columns; $col1++) {
$sql2 = "SELECT ID, sample, rack, srow, col, location FROM samples WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack' LIMIT 1";
if (!$result2 = $db->query($sql2)) {
die('There was an error running the query [' . $db->error . ']');
}
$row3 = $result2->num_rows;
//If location is empty, colout green
if ($row3 == 0) {
echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";
}
else {
//Location is not empty, colour red and link to sample
while ($row2 = $result2->fetch_assoc()) {
$columns1 = $row2['col'];
$ID = $row2['ID'];
$tooltip = $row2['sample'];
$queryStr = $_SERVER['QUERY_STRING'];
$spath = $_SERVER['PHP_SELF'] . "?" . $queryStr . "&sample=" . $ID;
echo <<<EOD
<td style="background-color: #FF0000" title="$tooltip">$col1 <img src="icon.png" style="border: 0" alt=""></td>
EOD;
}
}
}
echo "</tr>";
}
echo "</table>";
You can convert all data from DB directly into a php array with this code:
while(($PHPToPHP[] = mysql_fetch_assoc($SqlResult )) || array_pop($dataToPHP));
may be work for your code:
while(($dataToPHP[] = $result2->fetch_assoc()) || array_pop($dataToPHP))
And to see what it does use print_r($dataToPHP).
To manage the errors die('There was an error running the query [' . $db->error . ']'); and if ($row3 == 0) { echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";} to colorize, you need to make some tests to correctly manage.
You need an array with index like your where
SELECT ID, sample, rack, srow, col, location
FROM samples
WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack'
LIMIT 1";
Your array looks like:
$samples = array(
"$row1:$col1:$location:$rack" => array( 'id' => $id, 'sample' => $sample
)
Or you can use some hash array like:
$samples = array(
md5( "$row1:$col1:$location:$rack" ) => array( 'id' => $id, 'sample' => $sample
)
Insert all values once - than get it like
$val = $samples["$row1:$col1:$location:$rack"];
// or from hash array
$val = $samples[md5( "$row1:$col1:$location:$rack" )];
Attempting to display different data in a table, but am only gettting the most recent result. The only thing I have changed in my code is adding the >CURDATE rather than the most simple *. it has stopped displaying all of the results. can you help?
$result = mysqli_query($con,"SELECT * FROM tripdata WHERE date > CURDATE()");
while($row = mysqli_fetch_assoc($result))
{
echo "<table class='mainpics'>";
echo "<tr><td><a class='mainpic' href='". $row['pageurl'] ."'><img class='mainpic' src='" . $row['mainpic'] . "'/></a></td></tr>";
echo "</table>";
}
mysqli_close($con);
?>
I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}
I am using this code to display image from URL, but it is not working,
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++){
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src="<?php echo $row[$i]; ?>" width="60" height="60" alt="word" />';
echo '</td>';
}
?>
The result is, I get alt text only, and image is not displayed. also, I get error
Notice: Undefined offset: 1 in D:\wamp\www\demo\login\flashcard.php on
line 31
In my file
What I am trying is, to get 5 img url from database and display them in columns of a table..and what I guess is I am getting same img URL again and again...for 5 times..
Please give me guideline and tell me what I could be missing...
i have never seen someone loop through a query that way, i do it like this:
print "<table>";
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch LIMIT 5';
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
print '<tr>
<td>
<img name="myimage" src="'.$row[column_name_here].'" width="60" height="60" alt="word" />
</td>
</tr>';
}
print "</table>";
change column_name_here to the name of the column which store the image file name
edit: changed mysql_fetch_row to mysql_fetch_array <- that is why u got the same image all 5 times.
With mysql_fetch_row() your fetching the results one row at a time, since you only specified url_imgsrch in the SELECT statement, it will be an array with one single element, the value for url_imgrch. This is the reason for your error message. The for() loop tries to in turn read the first, second, etc up to fifth value of the array, which never gets updated with new information and always has only one element.
mysql_fetch_row() will return false when there is no more data to be read, you need to call it to fetch each new row of data, so what you want is to rewrite your code to something along the lines of this:
$sql = 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
while (false !== ($row = mysql_fetch_row($result))
{
echo '<td>';
echo '<img name="myimage" src=' . $row[0] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
The first part is just as you've written, setting up the SQL query and fetching a resource pointer ($result) to with mysql_query().
In the next part the while() loop will run for as long as $row is not false, updating $row with new data for each run of the loop. Since mysql_fetch_row() fetches an numerically indexed array, you want to retrieve $row[0], it's the first (and only) column you requested in the SQL query. There are many ways of writing the while() loop, but this way quite common, and easy to read for other developers.
try this:
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++)
{
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src=' . $row[$i] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
?>