I wrote this code to retrieve some rows form database
session_start();
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM student WHERE id = " . $_SESSION['user_id'] ." and password = " . $_SESSION['user_pass'];
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result))
{
echo "this academic transcripts for " . $row["name"];
echo " and the id is " . $row["id"];
}
$q1 = " SELECT student_record.course,student_record.grade,student_record.term,coe_courses.crd
FROM student_record INNER JOIN coe_courses ON student_record.course_number = coe_courses.course_number
where student_record.id = ".$_SESSION['user_id'] ;
$result = mysqli_query($con , $q1 ) ;
if($row = mysqli_fetch_array($result))
{
echo "<br />";
echo "<table border=\"1\" style=\"width:500\">";
echo "<tr>";
echo "<th>coe_courses</th>";
echo "<th>terms</th>";
echo "<th>Grades</th>";
echo "<th>CRD</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row["course"]. "</td>";
echo "<td>" . $row["term"]. "</td>";
echo "<td>" . $row["grade"]. "</td>";
echo "<td>" . $row["crd"]. "</td>";
echo "</tr>";
echo "</table>";
}
The problem is that only shows the first row while I have three rows in phpMyAdmin.
enter image description here
You need to call fetch_* repeatedly to retrieve all rows from your result set; each time you call it it retrieves the next row in the result set.
In your sample code above, you would replace
if ($row = mysqli_fetch_array($result))
{
with
while ($row = mysqli_fetch_array($result))
{
This will loop until fetch_array tries to read beyond the last record in $result, at which point fetch_array returns false and the loop exits.
Related
Thanks, friends, for the help and feedback. I know i am not good with PHP but still trying to learn and playing with it :D -- My table contains duplicate entries against evaid as Open Close or In Process --- with below code I get the last entered status from DB against each status by using query and if statement to show the data but i want to get the count of it as well. Anyone can help me out --- For example ---
$sql = "SELECT * FROM (SELECT * FROM disagreements ORDER BY addeddate DESC) disagreements GROUP BY evaid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) { // Here with this query I got last entered status of each row against evaid ā as 2 Open ā 5 in Process and 10 Closed --- with below if statement ā I can echo the rows with status but I want to have count of it that how many are open, in process or closed
if($row["status"]=='Open') { // I want to count this value as 2
echo "<tr>";
echo "<td>" . $row["evaid"]. "</td>";
echo "<td>" . $row["status"]. "</td>";
echo "</tr>";
}
}
} else {
echo "Nothing to Display";
}
mysqli_close($conn);
<?php
$count['open'] = 0;
$count['close'] = 0;
$count['process'] = 0;
while($row = mysqli_fetch_assoc($result)) {
if($row["status"]=='Open')
{
$count['open']++;
echo "<tr>";
echo "<td>" . $row["evaid"]. "</td>";
echo "<td>" . $row["status"]. "</td>";
echo "</tr>";
}
if($row["status"]=='Close')
{ // I want to count this value as 2
$count['close']++;
echo "<tr>";
echo "<td>" . $row["evaid"]. "</td>";
echo "<td>" . $row["status"]. "</td>";
echo "</tr>";
}
if($row["status"]=='Process')
{ // I want to count this value as 2
$count['process']++;
echo "<tr>";
echo "<td>" . $row["evaid"]. "</td>";
echo "<td>" . $row["status"]. "</td>";
echo "</tr>";
}
}
print_r($count);
?>
// Hii.. You can get a count from your SQL query itself, try this
$sql = "SELECT *, COUNT(ID) AS COUNT FROM (SELECT * FROM disagreements ORDER BY addeddate DESC) disagreements GROUP BY evaid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
if($row["status"]=='Open')
{
echo "<tr>";
echo "<td>" . $row['count'] . "</td>"; // here you will get a count
echo "<td>" . $row["evaid"]. "</td>";
echo "<td>" . $row["status"]. "</td>";
echo "</tr>";
}
}
}
else
{
echo "Nothing to Display";
}
mysqli_close($conn);
I am trying to create a basic advanced search with an input which will then search through any results that have a matching category field that is selected in the dropdown and then also a matching keyword field for company_name in "advancedSearch". I have gotten to the stage where I can use the drop down to then display the matching data but Iām having trouble querying that with the search input.
Here is my form code from index.php
<form action="advanced-search.php" method="POST">
<input id="advancedInput" placeholder="Advanced Search" type="search" name="advancedSearch">
<?php
$sqlSelect="SELECT category FROM categories";
$result = $db -> query ($sqlSelect);
echo "<select id=\"selectAdvanced\" name=\"value\">";
echo "<option></option>";
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
foreach ($rows as $row) {
print "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="search"/>
</form>
And here is the code from my advanced-search.php
<?php
if(isset($_POST['value']) && !empty($_POST['value'])) {
$username = trim(strip_tags($_POST['value']));
include('dbConfig.php');
if (mysqli_connect_errno()) {
printf("Can't connect: %s\n", mysqli_connect_error());
exit();
}
$where = ($username == "category")? "" : " WHERE category = '$username'";
$sql = "SELECT * FROM company_listings" . $where; // Create Query
$result = mysqli_query($db, $sql); // Run Query
echo "<table border=1><tr><th>id</th><th>name</th><th>created</th></tr>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['created'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
This code works great for echoing out the matching categories from the dropdown but I cant work out how I would further query the search from the "advanced search" input.
Any help would be greatly appreciated.
I worked out that using AND in my query like this and using the Request on submit I was able to get what I was after... Thanks to #ADyson for the nudge. I have added my updated advanced-search.php file below;
if(isset($_REQUEST['submit'])){
$username = (($_POST['value']));
$advanced = (($_POST['advancedSearch']));
include('dbConfig.php');
if (mysqli_connect_errno()) {
printf("Can't connect: %s\n", mysqli_connect_error());
exit();
}
$sql=" SELECT * FROM company_listings WHERE company_name like '%".$advanced."%' AND category LIKE '%".$username."%'";
$result = mysqli_query($db, $sql); // Run Query
echo "<table border=1><tr><th>id</th><th>name</th><th>created</th></tr>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['created'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
Finally jumping into some PHP for the first time and I've written this program and i'm stuck. I've searched all over the place for about 2 hours to find a solution.
Basically I'm connecting to my local database and trying to grab all the rows from my 'songs' table, and display them by their names. Instead of getting their names, i'm getting a notice that says "Notice: Array to string conversion in C:\xampp\htdocs\musiclibrary\index.php on line 47"
My current output looks like this:
Title Artist Genre
Array Array Array
Array Array Array
Array
And then my code is...
<?php
// Require configuration file
require_once 'config.php';
// Connect to the database
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
// Check for database connection error
if(!$db_server)
{
die("Unable to connect to MySQL: " . mysql_error());
}
// Select a database
// The mysqli_select_db() function is used to change the default database for the connection.
mysqli_select_db($db_server, $db_database);
$prompt = array('Story title', 'Time', 'Person');
$prompt = array('Story title', 'Time', 'Person');
// Page title
echo "<h1>My Music Collection</h1>";
// Get music collection
$query = "SELECT * FROM songs";
$result = mysqli_query($db_server, $query);
$rows = mysqli_num_rows($result);
// If rows exist
if($rows > 0)
{
// Create HTML table
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
for($j = 0; $j < $rows; $j++)
{
// Build HTML table row
//PROBLEM LIES HERE ON THESE MYSQL_FETCH_ASSOC PARTS
echo "<tr>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'title') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'artist') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'genre') . "</td>";
echo "</tr>";
}
echo "</table>";
}
// If there are no songs in the database table
else
{
echo "There are currently no songs on file.";
}
?>
Any solutions to output the names of the rows in my database? Thanks!
Use the code below to replace your code
extract the values to an array first
show the values in table row
$values = mysqli_fetch_assoc($result);
echo "<tr>";
echo "<td>" . $values ['title']. "</td>";
echo "<td>" . $values ['artist'] . "</td>";
echo "<td>" . $values ['genre')]. "</td>";
You need to loop the mysqli_fetch_assoc function to count row then loop the row result to get value
Here is the code :
if($rows > 0){
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
while($row = $result->mysqli_fetch_assoc()){
echo "<tr>";
foreach($row as $key => $value){
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
Hope it helps!
mysqli_fetch_assoc() function accepts only one parameter.
array mysqli_fetch_assoc ( mysqli_result $result )
Correct way to do this would be:
$query = "SELECT * FROM songs";
if ($result = mysqli_query($db_server, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "</tr>";
}
mysqli_free_result($result);
}
I am trying to let the user input an account number and below the business name will show.
Here is the code I am using which is called from the form:
<?php
$q = intval($_GET['q']);
$con = mysql_connect("localhost","cl49-xxx","xxx");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"cl49-xx");
$sql="SELECT * FROM member WHERE personID = '".$q."'";
$result = mysqli_query($con,$sql);
echo "Business Name:<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['businesstype'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
When I run this code it just shows business name:.
I think you have issue near while loop. Instead of "while($row = mysqli_fetch_array($result)) ". Why do not you use this:
$row = mysqli_fetch_array($result);
$i= 0;
while( $i<count($row))
{
echo "<tr>";
echo "<td>" . $row['businesstype'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
I have an admin area in an ecommerce website whereby the admin can view all users on the allusers.php page. The users are listed in a table with their personal information, however i have a 'view profile' button near each user whereby if you was to click on it, it would take you to another page where you can view that specific users past orders.
the following is the code i have for allusers.php:
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
the view.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM order WHERE ......dont know what to enter here")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>
I have a mysql database with the following fields & tables:
Customers - id, name, surname, address1, address2, city, postcode, email, username, password
Products - serial, name, description, price, picture
Order - id, name, quanitity, price, date, username
Thanks for any help provided
Your code lacks any sort of security mechanisms... This is very bad, especially in an e-commerce setting.
Excusing that, you would pass the username to the view page in the URL.
echo "<td>" . " <a href='view.php?user=" . $info['username'] . "'>View</a> </td>";
In your view page, you would get the parameter from the URL and include it with your query.
if (isset($_GET) && isset($_GET['user'])) {
$user = mysql_real_escape_string($_GET['user']);
} else {
header('Location: allusers.php');
exit(); // boot them back to the previous page.
}
$result = mysql_query("SELECT * FROM order WHERE username = '" . $user . "'")
A simple method could be the follow. Replace this line in alluser.php
echo "<td>" . " <a href='view.php'>View</a></td>";
with this one
echo '<td>View</td>';
and then, in your view.php have
if (isset($_GET['username']) && $_GET['username'] != '')
{
$username = mysql_real_escape_string($_GET['username']);
$result = mysql_query("SELECT * FROM order WHERE username = '$username'");
}
else
{
// No user specified. Do other statements
}
Please note the use of:
The user of the mysql_real_escape_string() function to protect from Sql injection (would be better the use of a prepared statements)
The use of the parameter username in the first page to pass the value of the username to the second page
The use of the $_GET global array to retrieve the parameter
Try this:
allusers.php
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php?user={$info['username']}'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
view.php
<?php
$user = mysql_real_escape_string($_GET['user']);
$result = mysql_query("SELECT * FROM order WHERE user = '$user'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>