How to make a table with MySQL queries - php

I'm trying to make a table that shows the results from a query of MySQL, but I'm having a hard time to get it right...
I had the PHP code to show the content of the database table with this script;
<?php
// Grab the data from our people table
$sql = "SELECT * FROM people ORDER BY ID";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"content/uploads/" . $row['filename']
. "\" alt=\"\" height=\"125\" width=\"200\" /><br />" . "<br />";
echo $row['fname'] . " " . "<br />" . "<br />";
echo "</p>";
echo "</div>";
}
?>
but that of course doesn't have tables which is pretty ugly as it displays everything underneath each other... so I tried to make a table for it and after a lot of research I found a script which should have displayed the content but I can't seem to implement it into my own code and ended up with the error:
Could not access DB: No database selected
Using this code:
<?php
$sql="SELECT * FROM people ORDER BY ID";
$result=mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num=mysql_numrows($result);mysql_close();?>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td>
<font face="Arial, Helvetica, sans-serif">Value1</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value2</font>
</td>
</tr>
<?php
$i=0;while ($i < $row) {$f1=mysql_fetch_assoc($result,$i,"field1");
$f2=mysql_fetch_assoc($result,$i,"field2");
$f3=mysql_fetch_assoc($result,$i,"field3");
$f4=mysql_fetch_assoc($result,$i,"field4");
$f5=mysql_fetch_assoc($result,$i,"field5");?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
</td>
</tr>
<?php
$i++;}
?>

Not sure what is going on here
mysql_fetch_assoc($result,$i,"field1")
Mysql_fetch_assoc only accepts one argument
The correct way to use it is as demonstrated in the php man page
while ($row = mysql_fetch_assoc($result))
{?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $row['value1']; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $row['value2']; ?></font>
</td>
</tr>
<?php
}
If you had errors and warnings turned on, then you would get helpful error messages telling you what was wrong with your code. It is always recommended to turn them on for development.

Related

display unrelated data from 2 tables

Trying to get data to display from 2 different and basically unrelated tables. Don't want them joined, just discrete output to look like this in a select box:
Category: current category from table1 (this part works)
Entire list of categories from table 2 (correct number of empty option tags, no data showing)
DB connection code:
//DB CONNECTION//
$dbcnx = mysqli_connect("localhost", $DBASEUSER, $DBASEPASSWORD, $DBASE);
//Main Showcase
$sql = "SELECT * FROM `dprods`";
//////HEADER in main page
<?php
$ID=$_GET['ID'];
$CAT=$_GET['cat'];
?>
//////Main SECTION
<?php
require "db_conn.php";
$sql2 = "SELECT * FROM $DBTABLE WHERE ID=$ID";
$getinfo = mysqli_query($dbcnx, $sql2);
$row = mysqli_fetch_assoc($getinfo);
$PROD = $row['dtitle'];
$PRICE = $row['dprice'];
$PP = $row['dpplink'];
echo "<tr>
<td width=\"12%\">
<div align=\"right\"><b><font face=\"Arial, Helvetica, sans-serif\" size=2>Product
Category: </font></b></div>
</td>
<td colspan=2 width=\"88%\"><select name=\"dcat\"><option value=\"$CAT\">Current Category: $CAT</option>";
$dcat = "SELECT * FROM 'dcat'";
$getcat = mysqli_query($dbcnx, $dcat);
$row2 = mysqli_fetch_assoc($getcat);
while($row2 = mysqli_fetch_assoc($result))
{ echo " <option value=\"".$row2["dcategory"]."\">".$row2["dcategory"]."</option>";
}
echo "".$row["dprice"]."</select>
</tr>
<tr>
<td width=\"12%\"> </td>
<td width=\"24%\"> </td>
<td width=\"64%\"> </td>
</tr>
<tr>
<td width=\"12%\">
<div align=\"right\"><b><font face=\"Arial, Helvetica, sans-serif\" size=2>Product
Title: </font></b></div>
</td>
<td width=\"24%\"> <b><font face=\"Arial, Helvetica, sans-serif\" size=2>
<input type=\"text\" name=\"Title\" value=\"".$row["dtitle"]."\" size=35 maxlength=25>
</font></b><b><font face=\"Arial, Helvetica, sans-serif\" size=2> </font></b></td>
<td width=\"64%\"><b><font face=\"Arial, Helvetica, sans-serif\" size=2>Price</font></b>:
<b><font face=\"Arial, Helvetica, sans-serif\" size=2>
<input type=\"text\" name=\"Price\" value=\"".$row["dprice"]."\" maxlength=10 size=20>
</font></b></td>
</tr>
<tr>
<td width=\"12%\"> </td>
<td width=\"24%\"> </td>
<td width=\"64%\"> </td>
</tr>
<tr>
<td width=\"12%\">
<div align=\"right\"><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=2><b>PayPal
Link: </b></font></div>
</td>
<td colspan=2><font face=\"Arial, Helvetica, sans-serif\"><b>http://www.paypal.com</b>
</font>
<input type=\"text\" name=\"PP\" value=\"".$row["dpplink"]."\" size=50>
<font face=\"Arial, Helvetica, sans-serif\">Only put in what follows paypal.com</font></td>
</tr>
";
mysqli_close($dbcnx);
?>
Been working and researching this for hours and now I'm so horribly confused, lupus induced Swiss-cheese brain isn't helping. I think I'm very close, just unable to get the data from the 2nd table to display. Would appreciate any suggestions, but please keep it as simple as possible. Some of the complex code I've seen in my research confuses me even more. Thanks!
Try including getcat in your select query like this:
$dcat = "SELECT 'dcategory', 'getcat' FROM 'dcat'";
$getcat = mysqli_query($dbcnx, $dcat);
while($row2 = mysqli_fetch_assoc($getcat))
{
echo " <option value=\"".$row2["getcat"]."\">".$row2["getcat"]."</option>";
}
echo "</select>"
You could also use $dcat = "SELECT * FROM 'dcat'";, but the above is likely slightly more efficient.
Also, I don't see where $result was being set for this code while($row2 = mysqli_fetch_assoc($result))
It looks like $result isn't set, so it would obviously give you undesirable results.
You're also doing $row2 = mysqli_fetch_assoc($getcat); outside of the while loop, which will grab the first row before entering the loop. The loop would start at the second row.
Please look at http://php.net/manual/en/mysqli-result.fetch-assoc.php
Also, your script will be subject to SQL Injection, as mentioned in the comments. You will need to fix it so it is as safe as possible. Read the links in the comments and also make sure you're using prepared statements
adpro, your help was invaluable. I was more confused than I realized and your comments helped point that out to me. I went back & started from scratch with a clean query code that I could print out, mark up with colored hi-liters to follow the variables. Code now works as desired and I'm posting for anyone else who may need the clarification. I appreciate the input from everyone about the sql injection. My goal was to get the simple functionality working first before making it more complicated. Now I can add the protection to prevent sql injection.
<?php
require "db_conn.php";
$sql2 = "SELECT * FROM $DBTABLE WHERE ID=$ID";
$getinfo = mysqli_query($dbcnx, $sql2);
$row = mysqli_fetch_assoc($getinfo);
$PROD = $row['dtitle'];
$PRICE = $row['dprice'];
$PP = $row['dpplink'];
echo "<tr>
<td width=\"12%\">
<div align=\"right\"><b><font face=\"Arial, Helvetica, sans-serif\" size=2>Product
Category: </font></b></div>
</td>
<td colspan=2 width=\"88%\"><select name=\"dcat\"><option value=\"$CAT\">Current Category: $CAT</option>";
$sqlCAT = "SELECT * FROM dcat";
if($resultCAT = mysqli_query($dbcnx, $sqlCAT)){
if(mysqli_num_rows($resultCAT) > 0){
while($rowCAT = mysqli_fetch_array($resultCAT)){
echo "<option value=\"".$rowCAT['dcategory']."\">".$rowCAT['dcategory']."</option>";
}
// Free result set
mysqli_free_result($resultCAT);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlCAT. " . mysqli_error($dbcnx);
}
echo " </select>";
mysqli_close($dbcnx);
?>

joined values from two tables with SQL but PHP does not show value on table

Sory to bother but I am loosing too much time on this: My sql query returns the table as I want it to, but for some reason I cannot get the result to appear on the table.
My SQL code:
$ssql = "SELECT * FROM tickets
JOIN (SELECT agencias.pais_id, paises.pais_nombre, agencias.EMP_CODE FROM agencias JOIN paises ON paises.pais_id = agencias.pais_id) agpais
ON tickets.cod_emp = agpais.EMP_CODE
WHERE tipo='NUE' ORDER BY id_ticket DESC" . $criterio;
$rs = mysql_query($ssql);
$total_registros = mysql_num_rows($rs);
PHP HTML code:
<?php
while($resz = mysql_fetch_array($rs)) { ?>
<td align="center" valign="middle" bgcolor="#C2DBE7"><font face="Verdana, Arial, Helvetica, sans-serif" size="1" color="#000000"> $resz[pais_nombre]</font></td>
<?php
}
?>
var_dump($rs) returns: resource(18) of type (mysql result)
<?php
while($resz = mysql_fetch_array($rs)) { ?>
<td align="center" valign="middle" bgcolor="#C2DBE7">
<font face="Verdana, Arial,Helvetica, sans-serif" size="1" color="#000000">
<?php echo $resz['pais_nombre'];>?
</font>
</td>
<?php
}
?>
If you specify something in html which is php code you have to put them in the php tags.That you forget to do and
<?php
//Php code goes here
?>
$resz[pais_nombre] requires single quotes around it like this $resz['pais_nombre']
It also needs PHP tags around it so <?php echo $resz['pais_nombre']; ?>

How do I display a query in PHP table

My code
<?php
include('ConnectToDb.php');
$query = "SELECT * FROM News WHERE NewsFlag = 1 ORDER BY PostDate DESC";
$arrCount = -1;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$ID=$row['ID'];
$PostDate = $row['PostDate'];
$NewsHeader = stripslashes($row['NewsHeader'])
;
$NewsStart = stripslashes($row['NewsStart'])
;
echo "<hr>";
echo "<div>". date('j F Y',strtotime($PostDate)). "</div>";
echo "<p>";
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
if(count($array)>0) {
echo "<img src='". $array[0]. "' alt='' />";
}
echo "<h2 style='text-align:center'><u><a href='latestnews_full.php?ID=$ID'>". $NewsHeader. "</a></u></h2>";
echo "<div style='text-align:left'><h3>";
echo $NewsStart. " ......<a href='latestnews_full.php?ID=$ID'>(more)</a><br />";
echo "<div style='text-align:center'>";
echo "</div>";
echo "</h3></div>";
}
?>
displays my data nicely on four lines with date at the top, then a picture, title and then description.
However, I want to display the data as a table like this
<table style="width: 100%">
<tr>
<td colspan="2">postDate here</td>
</tr>
<tr>
<td rowspan="2">picture here</td>
<td>newsHeader here</td>
</tr>
<tr>
<td>newsStart here</td>
</tr>
</table>
I'm not sure how to echo the table cells correctly and all of my attempts so far have resulted in a white page. Could anyone please enlighten me?
I'd suggest you to make your logic separated from your presentable part. Close the PHP tag once you are ready fetching the results, assigning var's etc, then:
<table style="width: 100%">
<?php
//yourcode
//...
//...
$NewsStart = stripslashes($row['NewsStart']);
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
?>
<tr>
<td colspan="2"><?= date('j F Y',strtotime($PostDate)) ?></td>
</tr>
<tr>
<?php
if(count($array)>0) {
?>
<td rowspan="2"><img src='<?= $array[0] ?>' alt='' /></td>
<?php } ?>
<td><?= $NewsHeader ?></td>
</tr>
<tr>
<td><?= $NewsStart ?> </td>
</tr>
<?php } ?>
</table>
However, it's again not so clear, and I would suggest using a template engine. If you want I can post a code with assigning vars to Smarty and output your presentation in Smarty template

PHP displaying individual tables

At the moment my produces results from a database and then inserts all of the results into one HTML table.
Is there any way that it would be possible so that for each result returned it created an individual HTML table (opposed to all of the results going into one HTML table)
My code:
<table class=\"board\" width='100%' border='0' align='center' cellpadding='1' cellspacing='1'>
");
$type = $_GET["type"];
if ($type == "" || $type == "request") {
$get = mysql_query("SELECT * FROM request WHERE type='Request' AND deleted != 'yes' ORDER BY id DESC");
} else {
if ($type == "shoutout") {
$get = mysql_query("SELECT * FROM request WHERE type='Shoutout' AND deleted != 'yes' ORDER BY id DESC");
} else {
if ($type == "competition") {
$get = mysql_query("SELECT * FROM request WHERE type='Competition' AND deleted != 'yes' ORDER BY id DESC");
} else {
if($type == "all") {
$get = mysql_query("SELECT * FROM request WHERE deleted != 'yes' ORDER BY id DESC");
}
}
}
}
$num = #mysql_num_rows($get);
if ($num == 0) {
echo ("<div class=\"board\"><center><font color=\"red\">There aren't any requests in this category!<br />
Why not ask listeners to send in their requests?</font></center></div>");
} else {
while ($r = mysql_fetch_array($get)) {
echo "
<tr>
<td><font face=\"verdana\" size=\"1\"><b>User</b></td>
<td><font face=\"verdana\" size=\"1\"><b>$r[habboname]</b></td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Date</b></td>
<td><font face=\"verdana\" size=\"1\">$r[date]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>IP</b></td>
<td><font face=\"verdana\" size=\"1\">$r[ip]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Message</b></td>
<td><font face=\"verdana\" size=\"1\">$r[message]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Type</b></td>
<td><font face=\"verdana\" size=\"1\">$r[type]</td>
</tr>
<tr>
<!-- <td><font face=\"verdana\" size=\"1\"><b>Refferer</b></td>
<td><font face=\"verdana\" size=\"1\">";
if($r[refferer] == 1){ echo "Site.com</td>"; } else { echo "Site1.com</td>"; }
echo "--></tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Commands</b></td>
<td><font face=\"verdana\" size=\"1\">Delete - Ban - <!--Alert-->Nominate LoTW</font></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
";
$id = htmlspecialchars($_GET['id']);
$delete = mysql_query("UPDATE request SET deleted = 'yes' WHERE id = '$id'");
}
echo ("</table></div>");
}
break;
case 'delete':
If you mean to create as many tables as there are returned rows, just put the opening <table> into the while's beginning and the closing </table> to the end of while. However, I don't understand why this would be desired. Do you really want to create many tables with just one row? It kind of defeats the purpose of a table. Make a list or use span's or anything else than tables instead.
while ($r = mysql_fetch_array($get)) {
echo "<table class=\"board\">
<tr>
<td><b>User</b></td>
<td><b>$r[habboname]</b></td>
</tr>
<tr>
<td><b>Date</b></td>
<td>$r[date]</td>
</tr>
<tr>
<td><b>IP</b></td>
<td>$r[ip]</td>
</tr>
<tr>
<td><b>Message</b></td>
<td>$r[message]</td>
</tr>
<tr>
<td><b>Type</b></td>
<td>$r[type]</td>
</tr>
<tr>
<!-- <td><b>Refferer</b></td>
<td>";
if($r[refferer] == 1){ echo "Site.com</td>"; } else { echo "Site1.com</td>"; }
echo "--></tr>
<tr>
<td><b>Commands</b></td>
<td>Delete - Ban - <!--Alert-->Nominate LoTW</font></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>";
$id = htmlspecialchars($_GET['id']);
$delete = mysql_query("UPDATE request SET deleted = 'yes' WHERE id = '$id'");
}
echo "</div>"; //remove () after echo
Update. One another thing. Please don't use inline styling. You have table class="board" so you already probably know the power of CSS.
Second update. I removed <font ...> tags. Use CSS for example like this:
table.board{
width:100%;
border:0;
align:center;
cellpadding:1;
cellspacing:1;
}
table.board td{
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: 1em;
}
CSS saves a lot of trouble when you want to change styling. And trust me, there will be a time when you want to change it (or your boss want's to bling-bling the site...).
ZZ-bb is absolutely right and as a hint try to put if/else construction in mysql - it will move faster or optimize it in php, like:
$get = mysql_query("SELECT * FROM request WHERE " . ($type == 'all' ? 'type = 1' : 'type = ucfirst($type)' ) . " AND deleted != 'yes' ORDER BY id DESC");

Applying a function to MySQL export to .txt

I'm exporting some data from MySQL which can be selected through checkboxes on a page to a .txt file.
Now I have a function to "black out" middle digits of the numbers from MySQL, this function is working on my page, there it looks like this:
<?php
$sql="SELECT * FROM table";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<?php function blankit($word) {
return substr($word, 0,2). str_repeat("X",strlen($word)-4) . substr($word, strlen($word)-2,strlen($word));
}
?>
<?php while($rows=mysql_fetch_array($result, MYSQL_ASSOC)) {
$code = ($rows['used'] == '') ? blankit($rows['code']) : $rows['code']; ?>
<tr class="first">
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $rows['id']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $code; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><? echo $rows['date']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $rows['ip']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $setusedpscde; ?></font></td>
<td class="tc"><input name="checkbox[]" type="checkbox" class="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
</tr>
<?php
}
?>
Now I want to apply this same function (blankit) when I export to the .txt file, my export code:
<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM table WHERE id='$export_id'");
$text2 = mysql_fetch_assoc($text);
$text3 = $text2["code"];
$filename = "export";
$filedate = date("Y-m-d");
$fileext = ".txt";
$fileall = $filename.$filedate.$fileext;
ob_end_clean();
header("Content-Type: application/octet-stream");
header("Content-disposition: attachment;filename=\"$fileall\"");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo chunk_split($text3, 16, "\n");
}
}
?>
I tried changing
$text3 = $text2["code"];
to
$text3 = ($text2['used'] == '') ? blankit($text2['code']) : $text2['code'];
But this X'ed out all the middle digits of every number, even if used was not =''
What do I have to change here ?
The problem is that for 1st query you selected all columns and in 2nd only the code column
$text = mysql_query("SELECT code FROM table WHERE id='$export_id'");
In that case, $text2['used'] == '' is always true as the value is null. You have to add 'used' column
$text = mysql_query("SELECT used, code FROM table WHERE id='$export_id'");

Categories