PHP MySQL How to skip displaying a field - php

I have the table MYTABLE that contains the fields: ID, PASSWORD, COL1, COL2, COL3, DATE
I would like to fetch and display all records in an html table but skipping ID and PASSWORD fields...
I'm using the following code which isn't working:
$query = "SELECT * FROM MYTABLE WHERE 1";
$results = mysql_query($query, $conn) or die(mysql_error());
echo "<tr>";
while ($r = mysql_fetch_assoc($results)) {
foreach ($r as $item) {
// let's not display ID and password
if ($r == 'ID' || $r == 'PASSWORD') continue; // this is the line that I want to figure out
echo "<td>$item</td>";
} // end for loop
} // end while
unset($item);
echo "</tr>";
Obviously there's more than 1 way to do it, for example I can replace the foreach loop with a for loop:
for ($i=0;$i<=6;$i++) {
if ($i == 0 || $i == 1 ) continue;
echo "<td>$r[$i]</td>";
} // end for
This will skip ID and PASSWORD fields but I don't want to use it, because I'm running the code on more than one table (table name is fetched from html select tag) and these tables may not have the same number of fields/columns (but they will always have ID and PASSWORD).
I can also do it with SQL statement (I don't want to), but then I'll have to query into a temp, drop the ID,PASSWORD columns and then fetch from the temp table. (by the way is there a compelling reason as to why I SHOULD in fact do it with SQL rathen than PHP?)

foreach ($r as $k => $item) {
// let's not display ID and password
if ($k == 'ID' || $k == 'PASSWORD') continue;
echo "<td>$item</td>";
}
This meets exactly your request.
I hope this result now useful to you, and after that, you evolve from it.

I would suggest you do it this way:
$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE 1";

Try this:
$query = "SELECT * FROM MYTABLE WHERE 1";
$results = mysql_query($query, $conn) or die(mysql_error());
echo "<tr>";
while ($r = mysql_fetch_assoc($results)) {
foreach ($r as $key => $item) {
// let's not display ID and password
if (!in_array($key, array('PASSWORD', 'ID'))) {
echo "<td>$item</td>";
}
} // end for loop
} // end while
echo "</tr>";

Let it easy..
<?php
$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE ..whatever..";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row["COL1"]."</td>";
echo "<td>".$row["COL2"]."</td>";
echo "<td>".$row["COL3"]."</td>";
echo "<td>".$row["DATA"]."</td>";
echo "<tr>";
}
}
?>

Related

for each statement only returns the word 'Array'

I'm creating a personal advisor page with 3 advisors in my database, I'm trying to create a dropdown box where someone can choose which advisor they'd like. At the moment my dropdown only displays the word 'Array' three times. Here's what I have so far.
<select name="advisor">
<?
$sqlQ = "SELECT concat(firstName,' ',lastName) FROM adv WHERE advisor IS NULL";
$array=array();
$res = $db->prepare($sqlQ);
$res->execute();
echo("<option>Advisor</option>");
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$array[] = $row;
}
foreach($array as $info)
{
echo("<option>$info</option>");
}
Your $row is already an array, so no need to insert your $row into a new array. Just loop the results like this
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $info)
{
echo("<option>$info</option>");
}
}
// give the result of concat() an alias so you can easily access it in the result set
$sqlQ = "SELECT concat(firstName,' ',lastName) as name FROM adv WHERE advisor IS NULL";
[...]
while ( $row = $result->fetch(PDO::FETCH_ASSOC) ) {
// $row is an array, its members correspond with the fields/aliases you've selected
// apply htmlspecialchars() so that the contents of $row['name'] can't break your html structure
echo '<option>', htmlspecialchars($row['name']), '</option>';
}

Every X result different while fetch from mysql database

I have simple php foreach loop which fetch some data from MySQL database
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
echo 'data';
}
As you can see there is LIMIT 30. Is it possible to to insert different data on every 10th result.Data which is not from database. It's static data and wont be changeable. What I mean is something like
if ( $row=10 )
{
echo $row['name'];
}
else
{
echo '<div> some static text not from database </div>';
}
$counter=0;
foreach ($result as $row)
{
$counter++;
if($counter %10==0){} //10th result
else{} //not 10th result
}
$counter = 0; //This is the counter which we will use to count row numbers.
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
$counter++; //We are incrementing the counter.
echo $row['name'];
//If we are at a row which is multiple of 10, we output a static value.
if($counter % 10 == 0)
echo 'Hello World!';
}

Checking result/count before outputting while loop

I'm looking for a way to SELECT from database, then check the result, and then output rows in a while loop (IF the result was above zero)
I really want to avoid using a separate count query
Right now I use this:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
$arr = $STH->fetchAll();
if (count($arr) > 0) {
echo '<div id="users">';
foreach ($arr as $row) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
It works. But isn't there a way I can check result/numrows and loop the rows, without using fetchAll and custom for-each loop?
Or does it not matter at all? (is for-each just as good as while loop?)
If I do it like this, the first row is not included in the while loop:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
if ($row = $STH->fetch()) {
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
EDIT: I DO need to check the result, for dynamic layout purposes
You can use the PDO method rowCount to verify before your foreach if there are rows
$STH = $conn->query($sql);
if ($STH->rowCount())
{echo '<div id="users">';
foreach ($STH->fetchAll() as $row)
{
echo '<h1>'.$row['username'].'</h1>';
}
echo '</div>';
}
http://php.net/manual/en/pdostatement.rowcount.php
note that this uses up a lot of memory as all your results are loaded at once in memory with fetchAll(). if you have very large result sets, consider using a while instead of the foreach
while ($row = $STH->fetch())
{// foo with $row
}
$row is being set to the first row of your results inside of your if statement. This means that your while loop will start at the second row.
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
The while loop will run if there is any results to fetch, and if there aren't, then respectively it won't run.

php mysql fetch array and loop rows

i have a database table 'movies'. in this table there are 25 columns of information per row. Ie, movie title, poster, cast, synopsis etc.
At the moment i am fetching the information like this
$query = "SELECT * FROM `movies` WHERE `title`='$moviename'";
$result = $con->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$moviedetails['title']=$row['title'];
$moviedetails['poster']=$row['poster'];
}
}
else {
echo 'NO RESULTS';
}
because i have 25 columns its long work writing out each variable. is there a way to fetch the information and i can then call to it by using
$moviedetails['column name']
ie
im new to php and mysql so any help appreciated.
thanks
lee
$moviedetails['title']
fetches the information from the 'title' column.
while($row = $result->fetch_assoc()) {
foreach ($row as $key => $value){
$moviedetails[$key]=$value;
}
}
This input the same key and the same value into new array
Is that what you're looking for?
$query = "SELECT * FROM `movies` WHERE `title`='$moviename'";
$result = $con->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($moviedetails = $result->fetch_assoc()) {
//just use moviedetails for what you need
}
} else {
echo 'NO RESULTS';
}
Try this:
while($moviedetails[]=$result->fetch_assoc()){}
then you loop by it like this:
foreach($moviedetails as $num->row)
{
echo $row['title'];
}

Generating a list of products based on database content

I've created a database which contains one table for each product series, basically I'm trying to list all the distinct models (table rows in each table), in a list where the first row is the table_name. Why does this not work?
$result = mysql_query("SELECT DISTINCT TABLE_NAME FROM
INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME
IN ('id') AND TABLE_SCHEMA='products-ropox'");
while($row = mysql_fetch_array($result))
{
$serie = $row["TABLE_NAME"];
echo "<ul>";
echo "<li class='ldd_heading'><a class='link'
href='products.php?category=".$serie."'>"
.ucfirst($serie)."</a></li>";
$query = mysql_query("SELECT DISTINCT model FROM $serie
ORDER by model ASC");
while($row = mysql_fetch_array($query))
{
echo "<li><a href='products.php?category=".$serie.
"&model=".$row['model']."'>".$row['model']."</a></li>";
}
echo "</ul>";
}
The first loop works well, but the second query generates an error...
Rename the second $row and you need mysql_fetch_assoc not mysql_fetch_array. If you want to use mysql_fetch_array you'll need to use $row[0]
$result = mysql_query("SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('id') AND TABLE_SCHEMA='products-ropox'");
while($row = mysql_fetch_array($result))
{
$serie = $row["TABLE_NAME"];
echo "<ul>";
echo "<li class='ldd_heading'><a class='link' href='products.php?category=".$serie."'>".ucfirst($serie)."</a></li>";
$query = mysql_query("SELECT DISTINCT model FROM $serie ORDER by model ASC");
while($row2 = mysql_fetch_array($query))
{
echo "<li><a href='products.php?category=".$serie."&model=".$row2['model']."'>".$row2['model']."</a></li>";
}
echo "</ul>";
}
Also a good pratice is to stick a or die(mysql_error()) after a query to output an error if there is one in your query.

Categories