PHP while command missing first entry - php

I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on.
<?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">
</head>
<body>
<div class="header">
<h2>Results.</h2>
<form action="watch.php" method='POST'><table>
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$vid = $row['vid'];
$source = "uploads/".$row['file_name'];
echo "<tr><td>".$row['vid']."</td>
<td>".$row['file_name']."</td>";
echo "<td><a href=watch.php?
source=$source>Play</a></td></tr>";
}
}else{
echo "0 results";
}
?>
</table></form>
<button class="button-block">Home</button>
</div>
</body>
I'd like it to print all matching criteria.
I'm getting only the entries after the first one.

require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
/*
This fetch_assoc will get your first row #0 of the query
next fetch_assoc with your loop on the $result
will start as you said from row #1
*/
$user = $result->fetch_assoc(); //your missing row #0
$_SESSION['file_name'] = $user['file_name'];

You missed a "}" at the end of your while loop, that might be a problem.. I also changed your >=1 of your num_rows conditions to > 0. Try this:
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$vid = $row['vid'];
$source = "uploads/" . $row['file_name'];
$htmlRow = "<tr>\n";
$htmlRow .= "<td>" . $row['vid'] . "</td>\n";
$htmlRow .= "<td>" . $row['file_name'] . "</td>\n";
$htmlRow .= "<td>" . $row['vid'] . "</td>\n";
$htmlRow .= "<td>Play</td>\n";
$htmlRow .= "</tr>\n";
echo $htmlRow;
}
}

Related

How to integrate array_column() and array_filter() into dynamic table generation of sql results

I want to read out data from an sql-database an show them in a table. This works well. Now, I would like to show only those columns with at least one value in it and not the empty ones (containing NULL, 0, empty string). This works with the following example:
enter code here
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM guestbook", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Home = array_column($results, 'Home');
$Date = array_column($results, 'Date');
$Emptycolumn = array_column($results, 'Emptycolumn');
$Comment = array_column($results, 'Comment');
$City = array_column($results, 'City');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Home)){echo "<TH>Home</TH>";}
if(array_filter($Date)){echo "<TH>Date</TH>";}
if(array_filter($Emptycolumn)){echo "<TH>Emptycolumn</TH>";}
if(array_filter($Comment)){echo "<TH>Comment</TH>";}
if(array_filter($City)){echo "<TH>City</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM guestbook", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Home)) {echo "<TD>".$line['Home']."</TD>";}
if(array_filter($Date)) {echo "<TD>".$line['Date']."</TD>";}
if(array_filter($Emptycolumn)) {echo "<TD>".$line['Emptycolumn']."</TD>";}
if(array_filter($Comment)) {echo "<TD>".$line['Comment']."</TD>";}
if(array_filter($City)) {echo "<TD>".$line['City']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
Since the column-names of my table are highly variable (depending on the query), the table is generated by looping through the result-array, first the column-names, then the values in the rows:
enter code here
$sql = "SELECT DISTINCT $selection FROM $tabelle WHERE
$whereclause"; //will be changed to PDO
$result = mysqli_query($db, $sql) or die("<b>No result</b>"); //Running
the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
if ($numrows > 0) {
echo "<table id='myTable' >";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== false){
echo "<th>" . $key . "</th>";
}else{
echo "<th>" . $field[$x]->name . "</th>";
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
Now, I tried to integrate the array_column() and array_filter()-blocks of the example above into the loops, but unfortunately, it didn´t work. I´m sure, this is easy for a professional and I would be very grateful, if someone could help me with this problem!
Thank you very much in advance!!

Writing the attributes of a database in PHP

I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>

Mysqli PHP - Display user info by id

I need help with this code bc im new with mysqli
i made a web to search a user and press a button to go link http://www.example.com/test.php?id=16 (16 is a example) but this code show me all the user and information of the database and i only need the information of the user with the id=16 for example.
I have done the part where i search the username and the button to send me test.php?id=16 <- id=16 is only a example bc can be any number
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b></p>
<?php
// connect to the database
include('connect-db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th></th><th></th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->id . "</td>";
echo "<td>" . $row->firstname . "</td>";
echo "<td>" . $row->lastname . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
</body>
</html>
Thanks for all :)
You have to pass the condition through the query like
$id = $_GET['id'];
if ($result = $mysqli->query("SELECT * FROM players WHERE id = ".$id)) {
And please note that ORDER BY is not required here.And to prevent SQL injuctions you have to mysqli_real_escape_string the GET string.
First of all get id value in a variable.
$id_val = $_GET["id"];
And correct your sql query.
"SELECT * FROM players WHERE id ='".$id_val."'"
use where clause in the query like
if ($result = $mysqli->query("SELECT * FROM players where=".$_GET['id']." ORDER BY id"))

how to insert multiple values of array checkbox in one row with different field name

i will use my old posted codes, coz i am working on the same program. what i want is how could i make it possible to save all selected values in one row which the studentid of a user will not be repeated. pls help...
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
echo 'Student ID: '. $voter.'';
echo "<br />";
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
global $voter;
$mysqli->query("INSERT INTO sample (studentid, candidate1) VALUES ('".$voter."', '". $ch ."')");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].checked)
{
return document.getElementById('candidates').innerHTML = document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->cand_studid ."' value='" . $row->cand_studid . "' onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
<table>
<tr><td>Preview List</td></tr>
<tr><td>Candidates: </td><td id="candidates"> </td></tr>
</table>
</body>
</html>
this the preview of my output and selected checkbox
now this is the preview of my database. this one is the result of my selection from the above preview which the student ID is repeated on my table.
what i want is to save like this
and one more thing, how could i make a preview of all i selected on the checkboxes, here is my preview output, below the table is the preview list of candidates as the user click on the checkbox. but it returns only one and only the last selected value as selecting multiple checkboxes will be printed. how could i apply this method in an array coz this preview, i remove the '[]' on my input type name='representative' and it works, but not in the presence of '[]'.
I don't know if I read your questions correctly, but...
For your Insert Issue
I don't know if the way you're storing the data in the database is the best method, but if you want to use what you have, you can just insert your record like this (assuming you've put in some validation script to prevent users from selecting more than 2 candidates):
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
if ($_POST['representatives']){
$check = $_POST['representatives'];
$mysqli->query("INSERT INTO sample (studentid, candidate1, candidate2) VALUES ('". $voter ."', '". $check[0] ."', '". $check[1] ."')");
}
}
?>
For your Preivew Issue:
I'm assuming you wanted something like this for your preview to show the studentid with the choices for candidate1 and candidate2:
<h3>Preview List</h3>
<table>
<tr><th>StudentID</th><th>Candidate 1</th><th>Candidate 2</th></tr>
<?php
$result = $mysqli->query("SELECT * FROM candidate_info");
while ($row = $result->fetch_object())
{
echo "<tr><td>" . $row->studentid . "</td><td>" . $row->candidate1 . "</td><td>" . $row->candidate2 . "</td></tr>";
}
$mysqli->close();
?>
</table>
Here is some pseudo code you can use to update the sample table:
$candidate=array(null,null);
$candidateCounter=0;
foreach ($check as $ch){
$candidate[$candidateCounter]=$ch;
$candidateCounter++;
if(candidateCounter>1){
something wrong, only 2 candidates can be selected
}
}
UPDATE sample set $candidate1=candidate[0], $candidate2=candidate[1] WHERE
studentid=$voter

Formatting Table with PHP

I can't figure out how to format my table so that there is a header for each section of attributes. I only see one header when there are actually more that I need to see.
For example I'm able to get DROID 4 by MOTOROLA and all of it's attributes go from Full Retail Price to Voice Dialing. After Voice Dialing there should be a second header for another phone. Clearly my logic is messed up and I have been struggling for about 4 hours on it. I also need the two tables to be side by side, not in a long list like this.
This is what I'm trying to achieve:
My code looks like this:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css" />
</head>
<body>
<?php
include_once 'config.php';
$conf = new config();
mysql_connect($conf->getdbServ(), $conf->getdbUser(), $conf->getdbPwd()) or die(mysql_error());
mysql_select_db($conf->getDB()) or die(mysql_error());
$selectedPhones = $_POST['phones'];
$totalSelected = count($selectedPhones);
//echo $totalSelected;
$idList = "";
for($i=0;$i < $totalSelected; $i++){
$idList .= $selectedPhones[$i] . ",";
}
$idList = substr($idList,0,-1);
$query = "Select name from ".$conf->getproductTbl()." WHERE id='$idList'";
$res=mysql_query($query);
//echo $idList;
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id IN(" . $idList . ");");
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</body>
</html>
1 - You might want to look into MYSQL JOIN to combine your two queries. (http://www.tizag.com/mysqlTutorial/mysqljoins.php)
2 - Use CSS to style your result set.
You can try something like this.. I hope that will help you.
<table>
<tr>
<?php
for($i=0;$i < $totalSelected; $i++){
//$idList .= $selectedPhones[$i] . ",";
?>
<td><?php
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id = ".$selectedPhones[$i]);
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</td>
<?php }?>
</tr>
</table>

Categories