I wonder if anyone can spot what is going wrong here? The first query has been tested and is working because I can print out the $groups array, but the 2nd one will not run. When I hard code the $groups array it runs fine.
require ('mysqli_connect.php'); // Connect to the db.
echo '<p>If no record is shown, this is because you had an incorrect or missing entry in the search form.<br>Click the back button on the browser and try again</p>';
//Coming from another page
$uninum=$_POST['uninum'];
$sname=$_POST['sname'];
$groups = array ( );
$count = count ($groups);
$q1 = "SELECT `groupid` FROM `groups`
WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
for ($i = 0; $i < $count; $i++){
$q = "SELECT participants.sname, participants.uninum,
groups.groupid
FROM participants
INNER JOIN groups ON
participants.uninum = groups.uninum
WHERE groups.groupid ='".$groups[$i]."'";
$result = #mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it ran, display the records.
// Table header.
echo '<table>
<tr>
<td><b>Edit</b></td>
<td><b>Surnname</b></td>
<td><b>University ID</b></td>
<td><b>Group</b></td>
</tr>';
// Fetch and display the records:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr>
<td>Edit</td>
<td>' . $row['sname'] . '</td>
<td>' . $row['uninum'] . '</td>
<td>' . $row['groupid'] . '</td>
</tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($result); // Free up the resources.
echo "<br><br>";
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
}
}
$groups = array ( );
$count = count ($groups);
$count is always equal zero
Try removing # with mysqli_query also $groups array will not start looping until your count is greater then zero.
if you var_dump($count) it will return zero.
$count = count ($groups);
var_dump($count);
You should count array after the query returns result set, right after ending while loop
$q1 = "SELECT `groupid` FROM `groups` WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
// count here
$count = count ($groups);
Related
I have this small code to display 200 rows and I want to give each row a number a per the no of votes.
How can I do it?
This is what I thought of but it does not work.
$sql = 'SELECT * FROM table LIMIT 200;
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$row = 1;
echo $row++;
echo $row['fullname'];
echo '<br>';
}
the output is making all row output to 1.
edit :
okay so some of the answers did the job but it does not work on the pagination. it counts from 1 on page 2,3,4,5.... heres the code.
<?php
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$result_per_page = 20;
$no_of_result = mysqli_num_rows($result);
$no_of_page = ceil($no_of_result/$result_per_page);
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
$page_first = ($page-1)*$result_per_page;
$sql = 'SELECT * FROM table LIMIT ' . $page_first . ',' . $result_per_page;
$result = mysqli_query($conn, $sql);
$num = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $num++;
echo $row['fullname'];
echo '<br>';
}
for($page=1;$page<=$no_of_page;$page++){
echo ''.$page.'';
echo ' ';
}
?>
Try to read your code line by line and see what it does.
while($row = mysqli_fetch_assoc($result)) { # > Set variable $row to the next result set or exit when there are none.
$row = 1; # Set variable $row to value 1.
echo $row++; # Increment variable $row to + 1.
echo $row['fullname']; # Row is now an integer, not an array. (You did that 2 statements ago)
echo '<br>'; #
} // end of loop, start again --------------|
A solution would be:
$id = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $id++;
echo $row['fullname'];
echo '<br>';
}
As for the page, you're overwriting the previous value:
for($s=$page;$s<=$no_of_page;$s++){
echo ''.$s.'';
echo ' ';
}
Why my while loop not working, I also have a while loop on the other PHP page, but there's only one page that doesn't work with PHP's while loop. But it does not contain any errors. Here's my code:
$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$num = mysqli_fetch_array($result);
if($num <= 0){
echo "<h2>No records found.</h2>";
}
$x=0;
while($row = mysqli_fetch_assoc($result)){
$x++;
echo '
<tr>
<td>'.$x.'</td>
<td>'.$row['permitno'].'</td>
<td>'.$row['boarding_optr'].'</td>
<td>'.$row['boarding_addr'].'</td>
<td>'.$row['orno'].'</td>
<td>'.$row['boarding_name'].'</td>
</tr>
';
}
You were reading your first result row and incorrectly using that as a count of resulted rows, then ignoring its content.
$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$num = mysqli_fetch_array($result);
// this reads the first row of your result set and then of course gets lost
//$num = mysqli_fetch_array($result);
// use mysqli_num_rows instead
if(mysqli_num_rows($result) <= 0){
echo "<h2>No records found.</h2>";
} else {
$x=0;
// now this will get the first row, which you must have been missing before
while($row = mysqli_fetch_assoc($result)){
$x++;
echo '
<tr>
<td>'.$x.'</td>
<td>'.$row['permitno'].'</td>
<td>'.$row['boarding_optr'].'</td>
<td>'.$row['boarding_addr'].'</td>
<td>'.$row['orno'].'</td>
<td>'.$row['boarding_name'].'</td>
</tr>
';
}
}
$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$x=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$x++;
echo '
<tr>
<td>'.$x.'</td>
<td>'.$row['permitno'].'</td>
<td>'.$row['boarding_optr'].'</td>
<td>'.$row['boarding_addr'].'</td>
<td>'.$row['orno'].'</td>
<td>'.$row['boarding_name'].'</td>
</tr>
';
}
}
else {
echo "<h2>No records found.</h2>";
}
I am struggling to understand why while loop not looping through the first query result.
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
$r2 = $stmt2->fetch(PDO::FETCH_ASSOC);
while ($r2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
I've read this thread but it is OOP. Any suggestions?
You already have fetched the first record by $r1 = $stmt1->fetch(PDO::FETCH_ASSOC);, and fetching the rest in while loop. This should work -
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
That's because you're fetching it twice. Remove the fetch just before while loop.
To something like this,
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
I am running a query on 2 tables, to return information from a blog. The nested query selects the tags that are associated with that blog, which is a separate table.
I want to be able to get the 'tag' row from the 'tags' table and display these on the page. My code is below and I have commented where I would like the rows to be selected.
<?php
include("inc/dbconnection.php");
$id = $_GET['tag'];
$id = trim($id);
$result = mysqli_query($conn, "
SELECT *
FROM blog
WHERE blog_id IN (SELECT blog_id FROM tags WHERE tag = '$id')
");
if (!$result) {
die("Database query failed: " . mysqli_error($conn));
} //!$result
else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$content = $row['content'];
$content2 = substr($content, 0, 100);
/* Below is where I would like to pull the row 'tag' from the nested query */
$rawTag = $row['tag'];
$tag = str_replace(" ", "", $rawTag);
$tagArray = explode(",", $tag);
$tag = "";
for ($i = 0; $i < count($tagArray); $i++) {
$tag .= "<a href='tag-" . $tagArray[$i] . ".php'>" . $tagArray[$i] . "</a> ";
} //$i = 0; $i < count($tagArray); $i++
echo "
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $content2 . "...</span><br />
<span><small>Tags: " . $tag . "</small></span>
</td>
</tr>
</table>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} //$rows > 0
else { //$rows > 0
echo "<br /><h1>There are currently no blogs with the selected tag (" . $_GET['tag'] . ")</h1><br /><h2>Please check back later.</h2>";
}
}
?>
Sorry if this is a stupid question and thanks in advance for your help :)
There are two part one is Query and second is data display.So Data display is total based
on your business call (how to display tag data in HTML.. )
but here you can optimize first part
(query for fetching data) as below:
$result = mysqli_query($conn, "SELECT b.*, t.* FROM blog b inner join tags t on
b.blog_id= t.blog_id WHERE t.blog_id '" . $id . "')");
Please use this.
usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!
Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}