Retrieving data from database from PHP - php

Trying to retrieve related data from the relationships table, after user clicks on the the bookname on the previous page. Nothing is being printed on the page even though in the database there is data.
The table schema is:
relationshipID,bookone,booktwo,relation,relationlike,relationdislike
<html>
<head>
<title>Retrieve Relationships</title>
</head>
<body>
<dl>
<?php
// Connect to database server
mysql_connect("latcs7.cs.latrobe.edu.au","12ice06","EsnYkuxuwh9RbtQuRcQt") or die (mysql_error ());
// Select database
mysql_select_db("12ice06") or die(mysql_error());
$sTitle=0;
// Get data from the database depending on the value of the id in the URL
$title = (isset($_GET['title']) && is_string($_GET['title'])) ? $_GET['title'] : null;
$sTitle = mysql_real_escape_string($title);
$strSQL = "SELECT R.bookone, B.title, B.author,
R.booktwo, B.title, B.author,
R.relation, R.relationlike, R.relationdislike
FROM relationships R
INNER JOIN books B ON R.bookone = B.bookid";
$rs = mysql_query($strSQL) or die(mysql_error());
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)){
// Write the data of the book
echo "<dt>Book One:</dt><dd>" . $row["bookone"] . "</dd>";
echo "<dt>Title:</dt><dd>" . $row["title"] . "</dd>";
echo "<dt>Author:</dt><dd>" . $row["author"] . "</dd>";
echo "<dt>Book Two:</dt><dd>" . $row["booktwo"] . "</dd>";
echo "<dt>Title:</dt><dd>" . $row["title"] . "</dd>";
echo "<dt>Author:</dt><dd>" . $row["author"] . "</dd>";
echo "<dt>Relationship:</dt><dd>" . $row["relation"] . "</dd>";
echo "<dt>Likes:</dt><dd>" . $row["relationshiplikes"] . "</dd>";
echo "<dt>Dislikes:</dt><dd>" . $row["relationshipdislikes"] . "</dd>";
}
echo $strSQL;
// Close the database connection
mysql_close();
?>
</dl>
<p>Return to the list</p>
</body>
</html>

if($row = mysql_fetch_array($rs)){
// Write the data of the book
echo "<dt>Book One:</dt><dd>" . $row["bookone"] . "</dd>";
echo "<dt>Book Two:</dt><dd>" . $row["booktwo"] . "</dd>";
echo "<dt>Relationship:</dt><dd>" . $row["relation"] . "</dd>";
echo "<dt>Likes:</dt><dd>" . $row["relationshiplikes"] . "</dd>";
echo "<dt>Dislikes:</dt><dd>" . $row["relationshipdislikes"] . "</dd>";
}while($row!=0);
Should be
while($row = mysql_fetch_array($rs)){
// Write the data of the book
echo "<dt>Book One:</dt><dd>" . $row["bookone"] . "</dd>";
echo "<dt>Book Two:</dt><dd>" . $row["booktwo"] . "</dd>";
echo "<dt>Relationship:</dt><dd>" . $row["relation"] . "</dd>";
echo "<dt>Likes:</dt><dd>" . $row["relationshiplikes"] . "</dd>";
echo "<dt>Dislikes:</dt><dd>" . $row["relationshipdislikes"] . "</dd>";
}

My advice:
a) Please reform the variable in your SQL-Statement like this:
$strSQL = "SELECT [...]
WHERE books.bookid=relationships.bookone
AND relationships.bookone='".$sTitle."'";
b) Make sure your variable $sTitle isn't empty. If it still is an issue, echo the whole SQL-Statement (echo $strSQL;) for further debugging.
c) While on it, please reform the whole SQL statement. The following statement does the same and is much more readable:
$strSQL = "SELECT R.bookone, R.booktwo,
R.relation,
R.relationlike, R.relationdislike
FROM relationships R
INNER JOIN books B ON R.bookone = B.bookid
WHERE R.bookone='".$sTitle."'";
d) Instead of outputting the data after if($row = mysql_fetch_array($rs)){, use a while-statement instead, something like
while ($row = mysql_fetch_array($rs)) {
// Write the data of the book
// Insert your echos here
}
e) Question:
Is there a specific reason table books is INNER JOINed, but not used in a condition?

Related

How do I echo a div using SQL table row ID as ID for the div?

I have this PHP code, which fetches data from my SQL database called "comments".
This code prints out every comment in the table:
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
}
echo '<div class = "white_line_comments"></div>';
} else {
echo "0 results";
}
This has worked fine so far, everything prints as it's supposed to.
Then I decided I wanted a way to give each individual comment some sort of identification to make them unique. I tried putting each single comment into its own div, using the SQLtable row id as id for the div.
However, when I try to access my webpage now, it tells me the website doesn't work (HTTP Error 500).
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='$row[' id'].'>";
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
echo '</div>';
}
echo '
<div class="white_line_comments"></div>';
} else {
echo "0 results";
}
Any ideas on this? I guess I must've done something wrong when including the div, but I can't figure out what!
You have an error in this line after starting while loop:
echo "<div class ='$row['id'].'>";
It should be
echo "<div class ='". $row['id'] ."'>";
You should also configure your web server/hosting/localhost to throw a PHP error.
Read this if you are on localhost or your own server:
How can I make PHP display the error instead of giving me 500 Internal Server Error
Read this if you are using shared hosting: How do I displaying details of a PHP internal server error?
echo "<div class ='$row['id'].'>";
First line in while loop should look like this
echo "<div class = '".$row['id']."'>";
or
echo "<div class = '$row['id']'>"
You have mixed different apostrophe, try this:
echo "<div class ='" . $row['id'] . "'>";

Displaying search results using mysqli multiquery

How can i display search results using mysqli multiquery. I want to display values from my listing-details table and from my user table. Here is my code:
$searchquery="SELECT * FROM `listing-details` WHERE `listing-address` LIKE '%" . $address . "%' AND `listing-address-street` LIKE '%" . $street . "%' AND `listing-address-barangay-id` LIKE '%" . $barangay . "%'";
$searchquery.= "SELECT `user.user-username`, `user.user-firstname`, `user.user-lastname`, `listing-details.user-username` FROM `user`, `listing-details` WHERE `listing-details.user-username`=`user.user-username`";
if (mysqli_multi_query($conn, $searchquery)) {
do {
if ($result=mysqli_store_result($conn,$searchquery)){
while($row=mysqli_fetch_row($result)){
$listingid =$row['listing-id'];
$username =$row['user-username'];
$listingbedquantity =$row['listing-bedquantity'];
$listingbedtype =$row['listing-bedtype-id'];
$listingguestsquantity =$row['listing-guestsquantity'];
$listingplacetype =$row['listing-placetype-id'];
$listingpropertytype =$row['listing-propertytype-id'];
$listingbathroomquantity =$row['listing-bathroomquantity'];
$listingaddress =$row['listing-address'];
$listingstreet =$row['listing-address-street'];
$listingbarangay =$row['listing-address-barangay-id'];
$listingamenities =$row['listing-amenities-basic-id'];
$listingsafetyamenities =$row['listing-amenities-safety-id'];
$listingsaphotos =$row['listing-amenities-safety-photos-id'];
$listingspace =$row['listing-space-id'];
$listinglandmark =$row['listing-landmark'];
$listingpreferences =$row['listing-preferences-id'];
$listingphotoset =$row['listing-photosset-id'];
$listingexperience =$row['listing-experience-id'];
$listingfrequency =$row['listing-frequency-id'];
$listingstartdate =$row['listing-startdate'];
$listingrate =$row['listing-rate-id'];
$listingprice =$row['listing-price'];
$listingrules =$row['listing-rules-id'];
$listingtitle =$row['listing-title'];
$listingdescription =$row['listing-description'];
$firstname =$row['user-firstname'];
$lastname =$row['user-lastname'];
echo "<ul>\n";
echo "<li>"."" . "<h2>" . $listingtitle . "</h2></li>\n";
echo "<li><h6>" . $listingaddress . ", " . $listingstreet . ", " . $listingbarangay . "</h6></li>";
echo "<li><i>" . $listingdescription . "</i></li>";
echo "<ul>\n";
echo "<li>"."" . "<h2>" . $listingtitle . "</h2></li>\n";
echo "<li><h6>" . $listingaddress . ", " . $listingstreet . ", " . $listingbarangay . "</h6></li>";
echo "<li><i>" . $listingdescription . "</i></li>";
echo "<li style='float:right;'>By: " . $firstname . " " . $lastname . "</i></li>";
echo "</ul>";
echo "<hr width='80%' noshade='1'>";
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($conn));
}
However, when I get to run it,the page loads, but results won't show. The purpose of it is to be able to display listing details from a listing-details table listed by the complete name from the user table. Two two tables have user-username column as common key.
Like many learners, you are using the wrong tool, simply because you don't know the proper one.
You need not a multiquery (which you never actually need anyway) but a JOIN.
Simply rewrite your two monster queries to a join like this
$searchquery="SELECT l.*, u.`user-username`, u.`user-firstname`, u.`user-lastname`
FROM `listing-details` l, user u
WHERE l.`user-username`=u.`user-username`
AND `listing-address` LIKE ...";
Besides, your quoting is wrong.

Php page not displaying

I am having a problem displaying a JOIN statement. When I add
WHERE id = " . $team_id;
The information that is on the database will not display, but when I remove that line the information will correctly join and display on the "teaminfo.php " page, but it will display all of the data instead of the data that is unique to that id. Also when I remove the JOIN the the data that is unique to the id will display. Can anyone tell me whats wrong here. Any help will be great. Than you.
teaminfo.php
<html>
<head>
<title>Team Info page</title>
</head>
<body>
<?php
include 'connect.php';
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
if ($result = mysqli_query($mysqli, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
// Write the data of the team
echo "<br />";
echo "Pit scouting";
echo "<dt>Team:</dt><dd>" . $row["pteam_number"] . " " . $row["pteam_name"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["pauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["pdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["pobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["pobjWithProblem"] . "</dd>";
echo "<dt>Can they shoot? If yes from where and how acc</dt><dd>" . $row["pshoot"] . "</dd>";
echo "<dt>Extra Notes about their robot?</dt><dd>" . $row["pdrive"] . "</dd>";
echo"<br />";
echo "Field Scouting ";
echo "<dt>Team Number:</dt><dd>" . $row["fteam_number"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["fauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["fdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["fobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["fobjWithProblem"] . "</dd>";
echo "<dt>Shots taken</dt><dd>" . $row["fshots_taken"] . "</dd>";
echo "<dt>Shorts made</dt><dd>" . $row["fshots_made"] . "</dd>";
echo "<dt>Extra Notes</dt><dd>" . $row["fnotes"] . "</dd>";
}
mysqli_free_result($result);
}
// Close the database connection
mysqli_close($mysqli);
?>
<p>Return to the list</p>
</body>
</html>
Palmetto.php
<?php
include 'connect.php';
// SQL query
$query = "SELECT * FROM pitscouting ORDER BY pteam_number";
if($result = mysqli_query($mysqli, $query)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$name = $row['pteam_number'] . " " . $row['pteam_name'];
// Create a link to teaminfo.php with the id-value in the URL
$strLink = "<a href = 'teaminfo.php?id= " . $row['id'] . "'>" . $name . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $query. " . mysqli_error($mysqli);
}
// Close connection
mysqli_close($mysqli);
?>
If your tables both have an ID field you will have to specify which table you want to get the data from.
WHERE pitscouting.id = " . $team_id;
or
WHERE fieldscouting.id = " . $team_id;
Please do mention the sql injection in you're code
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
please take a look at prepared statements, to prevent sql injections in youre code
Try putting an alias.
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting p
JOIN fieldscouting f
ON p.pteam_number = f.fteam_number
WHERE p1.id = " . $team_id;

php and mysql to xml

i have 2 tables, first one which stores restaurant info and second stores dishes served in each. They are linked using res_id.
1) info_main [id, res_id, res_name,res_pc]
2) dishes [id,dishName,price,res_id(Foreign key)]
My SQL query is
$query = "SELECT * FROM info_main LEFT JOIN dishes ON info_main.res_id = dishes.res_id";
I am inserting the results from the query into an xml file which works fine. Below is the code:
$query = "SELECT * FROM info_main LEFT JOIN dishes ON info_main.res_id = dishes.res_id";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker> ';
echo '<detail1>';
echo '<resdetails ';
echo 'name="' . parseToXML($row['res_name']) . '" ';
echo 'id="' . parseToXML($row['res_ID']) . '" ';
echo 'pc="' . parseToXML($row['res_pc'] ). '" ';
echo '/>';
echo '<dishdetails ';
echo 'name="' . parseToXML($row['dishName']) . '" ';
echo 'price="' . parseToXML($row['price']) . '" ';
echo '/>';
echo '</detail1>';
echo '</marker>';
}
This work fine however if a restaurant has 3 dishes in the database, then xml create 3 nodes: Something like this:
I want the xml structure like
<detail1>
<resdetails name="spoted dog" id="xyz" pc="xyz"/>
<dishdetails name="bean burger" price="1" />
<dishdetails name="cheese and tomato panini" price="3" />
<dishdetails name="veg salad" price="2" />
</details1>
I cant figure out a way how to achieve the above stated xml structure. Your help is greatly appreciated. Thanks
$query = "SELECT * FROM info_main LEFT JOIN dishes ON info_main.res_id = dishes.res_id";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
$resname = "";
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
if ($resname!=$row['res_name']) {
//restname isn't populated or doesn't match current so output new headers
echo '<marker> ';
echo '<detail1>';
echo '<resdetails ';
echo 'name="' . parseToXML($row['res_name']) . '" ';
echo 'id="' . parseToXML($row['res_ID']) . '" ';
echo 'pc="' . parseToXML($row['res_pc'] ). '" ';
echo '/>';
}
//this bit needs to always happen
echo '<dishdetails ';
echo 'name="' . parseToXML($row['dishName']) . '" ';
echo 'price="' . parseToXML($row['price']) . '" ';
echo '/>';
if ($resname!=$row['res_name']) {
//restname isn't populated or doesn't match current so output new headers
echo '</detail1>';
echo '</marker>';
}
$resname = $row['res_name']; //set resname to this res_name as this is our check to see if we've already put out required headers for this item that way every change it'll put this back in
}
Something like this (note may need some tidying up)
For that structure just do this:
echo '<marker> ';
echo '<detail1>';
while ($row = #mysql_fetch_assoc($result)){
echo '<dishdetails ';
echo 'name="' . parseToXML($row['dishName']) . '" ';
echo 'price="' . parseToXML($row['price']) . '" ';
echo '/>';
}
echo '</detail1>';
echo '</marker>';
All that is really different, is that I moved a portion of your code out of the while loop.
Atlast i got that working, i used two query's, one getting distinct restarant and other getting dishname. i used loop in the main loop. below is the code.
$query = "SELECT DISTINCT * FROM info_main";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$id=$row['res_id'];
// ADD TO XML DOCUMENT NODE
echo '<marker> ';
echo '<detail1>';
echo '<resdetails ';
echo 'name="' . parseToXML($row['res_name']) . '" ';
echo 'id="' . parseToXML($id) . '" ';
echo 'pc="' . parseToXML($row['res_pc'] ). '" ';
echo '/>';
$dishes = "SELECT * FROM dishes WHERE res_id = '" . $id . "'";
$dish = mysql_query($dishes);
while ($row2 = #mysql_fetch_assoc($dish)){
$id2 = $row2['res_id'];
echo '<dishdetails ';
echo 'name="' . parseToXML($row2['dishName']) . '" ';
echo 'price="' . parseToXML($row2['price']) . '" ';
echo '/>';
}
echo '</detail1>';
echo '</marker>';
}
echo '</markers>';

PHP/MYSQL: Pulling information from database

I have done a little bit of research on this, but currently I'm stuck.
My situation:
My database has a serverName, and serverBanner for each entry. When I do this following code:
function listBanner() {
include("mysql.php");
$votes = "serverVotes";
$results = mysql_query("SELECT * FROM toplist ORDER BY $votes ASC");
while($row = mysql_fetch_array($results)){
echo " " . "<img src=" . $row['serverBanner'] . " height=60 width=460 />";
}
}
If you noticed, it is pulling all the info from toplist table. I need to pull all the info from toplist table, but make it so that I can put each on if them in a table row. Right now if I did that, it would put each banner in the same table row.
Also, how would I go about implementing this into a table?
Do you mean:
<?php
echo "<tr>";
while($row = mysql_fetch_array($results)){
echo "<td>" . $row['serverName'] . "</td>";
echo "<td>" . "<img src=" . $row['serverBanner'] . " height=60 width=460 />"."</td>";
}
echo "</tr>"
?>

Categories