I have a table which contains the following columns..
And I stored the data of that table in a session variable
$sql = "SELECT * from `basic_info` where Username='".$user."' and Password='".$pass."'";
$sqlresult = mysqli_query($con,$sql) or die(mysqli_error($con));
$rowCount = mysqli_num_rows($sqlresult);
$currentData = mysqli_fetch_array($sqlresult);
if($rowCount > 0){
$_SESSION['currentUser'] = $currentData;
}
But whenever i echo the values of the array using below code:
<?php
echo "Welcome {$_SESSION['currentUser'][1]}";
echo "<div name='infoDisplay'>";
echo "<table>";
echo "<tr>";
echo "<td><b>Family Name</b><td>";
echo "<td><b>First Name</b><td>";
echo "<td><b>Middle Name</b><td>";
echo "<td><b>Birthday</b><td>";
echo "<td><b>Contact Number</b><td>";
echo "<td><b>Address</b><td>";
echo "<td><b>Username</b><td>";
echo "<td><b>Password</b><td>";
echo "<td><b>Permission Level</b><td>";
echo "<td></td>";
echo "</tr>";
echo "</table>";
echo "</div>";
echo "Array count: " . count($_SESSION['currentUser']) . "<br/>";
echo "<tr>";
for($rowcount=0; $rowcount<=count($_SESSION['currentUser']);$rowcount++){
echo "<td>". $_SESSION['currentUser'][$rowcount] . "</td>";
}
echo "</tr>";
?>
the array count is doubled. I only have 9 columns in my database but the result is returning 18 counts. Which why I'm also getting below error:
Please let me know your inputs on how can I easily resolve the issue. Thank you very much in advance! Have a great day!
As mentioned in the comments, mysqli_fetch_array returns an array with two elements for each column selected in the query: one element with a numeric key, and one element whose key is the column name. So if you select 9 columns, the array will have numeric keys from 0 to 8, and named keys FamilyName, FirstName, and so on.
The problem you're running into count($_SESSION['currentUser']) counts both of these elements, so it will return 18, not 9. Your for loop then uses this as the limit, so it will try to echo $_SESSION['currentUser'][9] through $_SESSION['currentUser'][17], which don't exist.
The solution to this is to use mysql_fetch_row() instead of mysql_fetch_array(). Or use mysql_fetch_assoc() and use a foreach loop instead of a for loop, which is my normal preference.
FROM THE MANUAL:
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
So for each row you return lets say you did select fname,lname from ...
You would get an array for each row like this:-
$row would be
[0 => 'fred', 'fname' => 'fred', 1 => 'Bloggs', 'lname' => 'Bloggs']
This is the doubling up of columns you are talking about
If you use
mysqli_fetch_array($sqlresult, MYSQLI_ASSOC);
or
mysqli_fetch_assoc($sqlresult);
You will only get the Associative array of column names like :
['fname' => 'fred', 'lname' => 'Bloggs']
Related
This question already has answers here:
Show values from a MySQL database table inside a HTML table on a webpage
(9 answers)
Closed 1 year ago.
I am new at php and am trying to learn CRUD applications. For this part of the code I have a table set up in a database (mysql). I am trying to interact with the table. I want a user to login (that part works) and when they are logged in- I store a message in $_SESSION that says ie. 'success'. This lets me know the user is logged in. Not the problem. The second piece is that IF there are rows IN THE TABLE already (from previous sessions) I want to print out these rows in a table. If there are no rows I want to print out "No rows"
I am trying to use simple logic here where first I create the $row variable by doing a fetch that comes from a pdo object(also fine). If that row is TRUE ie. it exists, print the table. If that row is false, print no rows. However, I keep getting the whole table printed, say 5 times. Instead of the 5 rows in the table.
Also, I am not sure I am using the correct type of while () statement. Which right now reads,
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
And then I get the WHOLE table and all rows 5 whole times. fetch and PDO::FETCH_ASSOC are a bit unclear to me, and I am understanding the $row as either true or false.
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( isset($_SESSION['success']) && $row == true ) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
echo "<tr><td>";
echo "Make";
echo ("</td><td>");
echo "Model";
echo ("</td><td>");
echo "Year";
echo ("</td><td>");
echo "Mileage";
echo ("</td><td>");
echo "Action";
echo ("</td></tr>");
echo "<tr><td>";
echo (htmlentities($row['make']));
echo ("</td><td>");
echo (htmlentities($row['model']));
echo ("</td><td>");
echo (htmlentities($row['year']));
echo ("</td><td>");
echo (htmlentities($row['mileage']));
echo ("</td><td>");
echo ('Edit'.'/'.'<a
href="delete".php?user_id='.$row['user_id'].'>Delete</a>');
echo "</td></tr>";
}
} elseif ( isset($_SESSION['success']) && $row == false ){
echo "No rows found";
}
I keep getting the whole table printed, say 5 times.
Because you're printing the whole table on each iteration of the loop:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
// etc.
Instead of checking whether the first row is true, check the row count:
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$count = $stmt->rowCount();
if ( isset($_SESSION['success']) && $count > 0 )
Then output your table outside the loop and just output each row inside the loop:
echo ('<table border="1">'."\n");
// etc, output the table header
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
// etc.
echo "</td></tr>";
}
echo ('</table>'."\n");
I'm trying to display the total number of records returned from my mongo 3.4 database. For this particular query, the results should be 380 but it's showing 14489. I'm sure it's something simple that I'm missing / forgetting about PHP
Here's the code: (including some debug statements about the type of variable I'm dealing with)
$numrecords = count($records);
echo"<BR><font color=red>".gettype($records)."</font>";
echo"<BR><font color=red>".sizeof($records)."</font>";
if ( $numrecords > 0 ) {
echo "<tr><td colspan='5'><h3>Record Count: ".$numrecords ."</h3></td></tr>";
echo "<tr><th>PH Number</th><th>Department</th></tr>";
foreach ( $records as $rec ) {
if (!empty($rec->department)) {
echo "<tr>";
echo "<td>". $rec->phnum . "</td>";
echo "<td>". $rec->department . "</td>";
echo "</tr>";
}
} //end for
} else {
echo "<tr><td colspan='5'>No matching data</td></tr>";
}
It says the object type is 'array'. I've been playing with count() vs. sizeof()
Any tips would be appreciated.
So it shows the correct number of rows in the table, but the count shows more than what's in the displayed table?
Try to use msqli_num_rows after your query
Here's an example below, you'll have to change it to your needs since you didn't provide your query code
$sql = "SELECT * FROM table_name WHERE datarow='$datarow'";
$result = mysqli_query($conn, $sql);
//this is where you count the number of rows returned from this query.
$count = mysqli_num_rows($result);
If this doesn't work, there's a problem with your query not meeting the specifications that you desire.
PHP and MySQL:What causes a query to exclude the first record in a table:
for example i have a script like this:
$query = "SELECT * FROM cars WHERE car_name = 'BMW'";
$results = mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Vehicle Name:<th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
$name = $row['car_name'];
echo "<tr>";
echo "<td>$name<td>";
echo "</tr>";
}
echo "</table>";
All rows are returned except the first one.Please help a brother out folks.
Not an answer, but too long for a comment:
Let's take a peak at your table cars.
What does
$qs = array(
array('total #rows', 'SELECT Count(*) FROM cars'),
array('#BMW', "SELECT Count(*) FROM cars WHERE car_name='BMW'"),
array('#LIKE BMW', "SELECT Count(*) FROM cars WHERE car_name LIKE '%BMW%'"),
array('#car_names', "SELECT Count(*) FROM (SELECT distinct car_name as foo FROM cars) as bar")
);
foreach( $qs as $query ) {
echo $query[0], "<br />\r\n";
$result = mysql_query($query[1]) or die(mysql_error());
while ( false!==($row=mysql_fetch_row($result)) ) {
echo ' ', $row[0], "\r\n";
}
}
print if placed in your script instead of your posted code?
The output should be something like
total #rows<br />
6
#BMW<br />
2
#LIKE BMW<br />
3
#car_names<br />
4
BTW: the mysql_* extension is deprecated,
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
EDIT
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same name,
you must use the numeric index of the column or make an alias for the
column. For aliased columns, you cannot access the contents with the
original column name
You are using mysql_fetch_array and this is what it says in the documentation. I never use mysql* functions so I wouldn't have jumped to this type of conclusion quickly. Use mysql_fetch_assoc($results) and I'm 99% sure it will resolve your issue. The why this would be different is in the paragraph above from the documentation. I assume your first row is identical to at least 1 of the below rows. Which means it is very likely you're missing more than just the first one. May or may not be the case.
END EDIT
Add 4 things to your code.
echo "<tr>";
echo "<th>ID</th>"; // THIS
echo "<th>Vehicle Name:</th>"; // Add closing tags........
echo "</tr>";
echo mysql_num_rows($results); // THIS (compare this to your MYSQL output row count)
while($row = mysql_fetch_array($results)){ **THIS... you have $results set with query, but $result here*** make sure both are $results OR $result
$id = $row['YOUR_AI_ID']; // THIS
$name = $row['car_name'];
echo "<tr>";
echo "<td>$id</td>"; // THIS
echo "<td>$name</td>"; // Add closing tags.......
echo "</tr>";
}
Go go do now. Come back with results.
Coming back to my project after putting it down for a while: Cycling through a query.
I understand that the below code can be cleaned up (PHP usage and table arrangement) and that MySQL commands are deprecated. ( I am working on that part).
But I can't see why I can't make this work. The print_r() gives Resource ID #5 error. My results show 2 tables, each with identical results all from the same course. I am expecting 8 tables, each table with a different course.
Should I use a while loop? if so how? I realize this is elementary, but this is still all new to me so please be gentle.
<?php
include 'inc.php';
$varVeh=$_POST['Veh_num'];
$sql_course="select course_num from hc_course";
$results_course=mysql_query($sql_course);
print_R($results_course);
foreach(mysql_fetch_array($results_course) as $rc)
{
$sql_HiScores = "SELECT c.course_name as course, e.distance as distance, e.score as score, e.time as time, e.user as User from hc_entries e left join hc_course c on e.course=c.course_num WHERE c.course_num=$rc and e.vehicle=$varVeh ORDER BY course, score DESC ";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="select Veh_name from hc_vehicle_type where Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
}
?>
mysql_fetch_array just returns one row of the results, not all the rows. Your foreach loop is just looping over the columns in the first row of results.
If you want to process all the results, you should write:
while ($rc = mysql_fetch_array($results_course))
Then inside your loop, you use $rc['course_num'] to get the course from that row.
But I don't understand why you need that first loop at all. You're JOINing the hc_courses and hc_entries tables in the first query inside the loop. Why don't you just use that same query, but without the c.course_num = $rc condition, so it gets all courses at once instead of doing them one course at a time? Loop over those results, and start a new table every time the course number changes.
Here's the query for that:
SELECT c.course_name as course,
e.distance as distance,
e.score as score,
e.time as time,
e.user as User,
c.course_num as course_num
FROM hc_entries e
JOIN hc_course c ON e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC
The PHP then looks like:
$last_course = null;
while ($row = mysql_fetch_assoc($results_HiScores) {
if ($row['course_num'] !== $last_course) {
// New course number, start a new table
if ($last_course !== null) {
// Close out last table, if any
echo '</table>';
}
$last_course = $row['course_num'];
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
}
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
echo "</tr>";
}
if ($last_course !== null) {
echo "</table>";
}
And you shouldn't do the hc_vehicle_type query inside the loop. It doesn't use any variables that change during the loop, it's just looking up the name of $_POST['Veh_num']. Just do it once and reuse the result inside the loop.
try:
foreach(mysql_fetch_array($results_course, MYSQL_ASSOC) as $rc)
{
....
}
if second argument is not given, MYSQL_BOTH is assumed, so array has column name, and column number 0,1...,n . so you traversed result set twice (column name and column number)
RTMF : http://us1.php.net/manual/en/function.mysql-fetch-array.php
and The print_r() gives Resource ID #5 error this is not an error!. return value of mysql_query() is result set. it's just a Resource of PHP internal structure.
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>";