display unrelated data from 2 tables - php

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);
?>

Related

How to make a table with MySQL queries

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.

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']; ?>

Php Delete item from mysql data base

Hope some one can help me out here, i guess am not calling my functions right.
Am trying to retrieve some data from my database and have a delete link attached to each items being retrieved, so that when ever i click on delete, it will delete that particular item which have the delete function.
My Code to retrieve items from database are as follows.
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
And my code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = $_GET['id'];
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
header("Location: vacct.php");
?>
I know am missing out the logic here and hope somebody can direct me or show me the easy way out. at the moment i can successfully retrieve my items from the data base my only problem is to be able to apply the delete function each time the delete button is tapped.
You have to pass the id when you click on the delete link:
<a href=\"delete.php?id=$z[theIdKey]\">
Use the below code.I have added validation and encryption
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = base64_decode($_GET['id']);
if(!empty($id)){
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
}
header("Location: vacct.php");
?>
<td>delete</td>
How are you passing the id to delete to your delete.php script?
Change:
<td>delete</td>
to:
<td>delete</td>
if $z[0] is the ID.
In your delete.php, make sure you also escape the word "transaction" using backtick:
DELETE FROM `transaction` WHERE id=123
this is because "transaction" is a reserved mysql keyword.
Please also read on SQL Injections.

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");

How can I get it so at the top of my search results page it says the amount of results found?

I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}

Categories