For some reason I'm having a problem retrieving data from my database. It leaves off the first item being listed.
$sql=mysql_query("SELECT * FROM students WHERE (year = '" . mysql_real_escape_string($_SESSION['year']) . "') and ( branch= '" . mysql_real_escape_string(($_SESSION['branch'])). "') ");
$data=mysql_fetch_array( $sql );
print "<table>"
while($data = mysql_fetch_array( $sql ))
{
Print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td></tr>";
}
print "</table>"
Please help me with this. Thank you.
Remove the following line:
$data=mysql_fetch_array( $sql );
The call to mysql_fetch_array moves the internal pointer to the next row, thus you are getting all rows except the first in your while loop.
You could also reset the internal pointer with mysql_data_seek.
mysql_data_seek ($sql, 0); // 0 for first row
It's because you use mysql_fetch_array one time before your while. The first call will get the first result, and then you will enter into the while loop. the $datavariable will erase the first result to be assigned by the second result and then the third, the fourth and so on.
Because of this call before the while loop, you will always avoid the first result
Related
I have a row named trailers in a MySQL database and I am querying that table using PHP and storing the result of that query in a variable. After that ,I am using a foreach loop to parse through each value of the variable i.e. each and every trailer value in the table.
But the problem is, when I try to echo the values of the variable only the first value of the variable is getting echoed in place of all other value. This is the query.
$query1 = "SELECT title,img,ratings,star_cast,director,trailer,imdb_ratings,lifetime_collecton,whats_good,whats_bad,watch_or_not
FROM recent_movies";
$result1 = mysqli_query($connect, $query1);
This is the code of the for each loop
<?php
foreach($result1 as $r):
echo $r['trailer'];
endforeach;
?>
Ten same values are getting printed instead of 10 different values.
Use the mysqli_fetch_array function to retrieve rows from a mysqli resultset.
Reference: http://php.net/manual/en/mysqli-result.fetch-array.php
$result1 = mysqli_query($connect, $query1);
while( $row = mysqli_fetch_array($result1,MYSQLI_ASSOC) ) {
echo "<br> " . $row['title'] . " " . $row['ratings'] ;
}
I'm going through Head First PHP and I've found this snippet of code in PHP.
It's supposed to display each row of records from a table containing the first_name, last_name and email.
while($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . ' ' . $row['last_name'] .
' : ' . $row['email'] . '<br />';
}
The $row array contains the next row obtained by mysqli_fetch_array(). But how is this a condition to be checked by the while loop? What exactly does the while loop evaluate to be true/false, before running the inner code? And why exactly does the loop stop when the rows have exhausted? There isn't even a condition to check for an EOF!. So how exactly does this work?
Referring to the PHP Documenation, mysqli_fetch_array() "Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset." So, when there are no more results, it returns null which evaluates to false and ends the loop.
I have a form on a html page which allows me to select multiple items. The name of the form is name="region[]
It posts to another page where I use this code:
The region(s) selected:
<?php
$values = $_POST['region'];
foreach ($values as $region){
echo $region;
}
?>
This will display the results of the form perfectly; if there is one value it will print the one value, but if there is more than one then it will print them all.
I need to use the results of this in a query:
<?php
$con=mysqli_connect("****","****","****","****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT
GoogleBusinessData.BusName,
GoogleBusinessData.BusAddress,
PostcodeTbl.PostcodeFirstTown,
PostcodeTbl.PostcodeFirstArea,
PostcodeTbl.Region,
PostcodeTbl.Postcode,
PostcodeTbl.PostcodeFirstLetters,
PostcodeTbl.PostcodeFirstPart,
PostcodeTbl.Country,
GoogleBusinessData.BusPhone,
GoogleBusinessData.BusCats,
GoogleBusinessData.FaroukCat,
GoogleBusinessData.BusWebsite,
GoogleBusinessData.BusDescription,
GoogleBusinessData.BusGoogleBusinessID,
GoogleBusinessData.BusPageURL,
EmailTable.EmailNumberOfEmails,
EmailTable.EmailAddresses
FROM
GoogleBusinessData
INNER JOIN PostcodeTbl ON GoogleBusinessData.BusPostalCode = PostcodeTbl.Postcode
INNER JOIN EmailTable ON GoogleBusinessData.BusWebsite = EmailTable.EmailWebsite
WHERE EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
GROUP BY
GoogleBusinessData.BusWebsite
ORDER BY
GoogleBusinessData.BusName ASC
LIMIT 0,20");
while($row = mysqli_fetch_array($result))
{
echo $row['BusName'] . " - " . $row['PostcodeFirstTown'] . " - " . $row['PostcodeFirstArea'] . " - " . $row['Region'] . " - " . $row['Postcode'];
echo "<br>";
}
mysqli_close($con);
?>
So I need to add the condition in the WHERE to only return the results if it contains one of the regions with the form. I tried the following with no joy:
WHERE PostcodeTbl.Region IN ('$region') AND
EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
But this only returns the last selection (as if there were only one selected).
Can anyone help?
In your first script, you are looping through the items. Each item is put into the variable $region one by one. So after the loop, $region contains the last item. If you construct the where clause at that time, it explains why the query only returns the last item.
To fix this, you'll have to construct a variable (e.g. $regions) that contains a list of regions.
For instance:
$regions = "'" . implode($_POST['region'], "','") . "'";
... WHERE PostcodeTbl.Region IN ('$regions') AND ...
Note that this is potentially unsafe, since the input in $_POST is not validated, so it is better to loop through the array (like you did) and validate each item one by one while constructing the string in $regions. You can use mysqli_real_escape_string for that.
Alternatively, and arguably better, is to use the parameter binding capabilities of mysqli. This is a bit tricky with array variables, but the details on how to do that are already described in this question.
So I have been looking for ways to display data from a database. However, they all require a loop and I do not want a loop as I only have 1 row in this table.
I came across mysqli_fetch_row() but I am not sure how to implement this. I am starting to learn PHP and MySQL and so any help is appreciated! This is what I have so far...
$displayIntro = mysqli_query($connection,"SELECT * FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo $displayTitle['Title'];
echo $displayTitle['Description'];
Also after displaying the plain text, how can I format it with HTML? For example, the title will need to be enclosed in <h1></h1> and the subscription in paragraph <p></p>.
Much thanks to any answers!
The problem is mysqli_fetch_row returns enumerated results, array with numeric indexes, so this should be like:
$displayIntro = mysqli_query($connection,"SELECT `Title`,`Description` FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo $displayTitle[0]; // assuming column 'Title' is first row
echo $displayTitle[1]; // assuming column 'Description' is second row
What you should use here is mysqli_fetch_assoc to fetch a result row as an associative array:
$displayIntro = mysqli_query($connection,"SELECT `Title`,`Description` FROM Introduction");
$displayTitle = mysqli_fetch_assoc($displayIntro);
echo $displayTitle['Title'];
echo $displayTitle['Description'];
Use code from #Maximus2012 answer to form html row. Also to get only one row from table with more than one records you can just add LIMIT 1 at the end of the MySQL query like this:
"SELECT `Title`,`Description` FROM Introduction LIMIT 1"
Hope this helps :)
From PHP manual entry for mysqli_fetch_row (link):
"Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero)." The function returns an enumerated array, not associative array.
Untested, but I would expect this to work:
echo $displayTitle[0];
echo $displayTitle[1];
$displayIntro = mysqli_query($connection,"SELECT * FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo "<html>";
echo "<body>";
echo "<h1>" . $displayTitle['Title'] . "</h1>";
echo "<p>" . $displayTitle['Description'] . "</p>";
echo "</body>";
echo "</html>";
This is for a timetable and what it does is displays the previous day's timetable and who has booked each slot (this is for a radio station.)
At the moment it displays who has booked each slot in chronological order however I would like it to say the time next to each result. The query outputs 24 rows (which is from Midnight to 23:00) and next to each slot I would like it to say (00:00, 01:00, 02:00, 03:00... 21:00, 22:00 so on so forth.)
This is my current code:
<?php
include("../config.php");
#// Timetable Clearup Variabls
$yesterday = strtotime('yesterday');
$yesterdow = date('l',$yesterday);
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE day = '$yesterdow'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
?>
Can you help?
I think we're all looking too hard at a VERY simple problem. You are already using SELECT * in your query, so you're already fetching all three columns from your table. So now, all you need to do is add another cell to each row of your table.
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['time']) . "</td></tr>";
And to make sure you are fetching your rows in the correct order, you should add an ORDER BY to your query:
SELECT * FROM timetable WHERE day = '$yesterdow' ORDER BY time
If you don't specify an ORDER BY clause, you have no guarantee that you will get the results in any particular order.
And one last thing, you are looping through the rows twice, unnecessarily. Get rid of the foreach loop and put the echo directly inside the while loop.
try this:
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . htmlspecialchars($row['time'])"</td></tr>";