I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}
Related
I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.
everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).
//DB CONNECTION
$sql = "SELECT `city`,`country` from infotab";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["city"].$row["country"]"<a href='order.php'>order</a>"; }
Table output:
This code will select data. Additionally, there is reference to order.php on every line. When the user clicks on reference( <a href> clause), it opens order.php and there I need to know which row the user selected to work with these data.
Change the code to:
while ($row = $result->fetch_assoc()) {
echo $row["city"] . $row["country"] . "<a href='order.php?city=" . $row["city"] . "&country=" . $row["country"] . "'>order</a>";
}
In order.php you can then access these values by using the $_GET["city"] and $_GET["country"] variables which contain the values from your <a href> link on the previous page. For example, running echo $_GET["city"]; will output the city name.
Edit: As #Rizier123 pointed out, using a unique ID might be more prone to errors in case your database contains more than one entry for the same city or country. You should consider introducing an ID in your table structure and then using that in the link to order.php.
I hope someone can help me with this?
I have a Joomla installation running and the website looks and works great.
Here's the problem, the website is for a car dealership, which means they need to display a list of their stock on the floor.
They are using a custom system to manage their stock and this system saves the data to a MS Access database.
I got it to work to a point where I can display a table from the database. (http://www.autodeal.co.za/newsite/used-car-sales-south-africa).
Now when someone clicks on the model, which is a link that will take them to another page which displays only the information relevant to the selected model.
That's what I can't figure out. The link works fine and it takes me to the page that I want, but it doesn't display the data like it's supposed to.
Please see the code below for connecting to the database and displaying the results:
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ORDER BY Make";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
echo "\t" . "<tr>\n";
echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";
while (odbc_fetch_row($rs))
{
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$year = odbc_result($rs, Year);
$price = odbc_result($rs, Price);
$specialPrice = odbc_result($rs, SpecialPrice);
$branch = odbc_result($rs, Branch);
$stockNo = odbc_result($rs, StockNO);
echo "\t" . "<tr>\n";
echo "\t\t" . "<td>" . $make . "</td><td><a href=http://www.autodeal.co.za/newsite/selected-vehicles>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";
echo "\t" . "</tr>\n";
}
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
Please see the code below to display a specific vehicle information from the table based on a selection made from the above script.
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$selected_id = intval($_GET['Id']);
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO, MainPic FROM Vehicle WHERE Id = Id";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
echo $make;
echo $model;
$image_path_main = "<img src=db/vehicleImages/" . $mainPic . "/>";
echo "this is a test";
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
EDIT So I've updated the above code based an answer received, but the individual records aren't displayed. I printed a test line and that works fine, so that tells me that there's an issue with the query? The thing is, the query works fine to display all the records in a table, but I need to display a single record when that record has been clicked.
Furthermore, the $mainPic variable above is referencing the image name from the database. The actual image isn't saved in the database; it's in a different location. I assume I need to create a variable with the actual path of the image and use the reference variables above to display the image, but it's not working.
So to recap, I need some help displaying all information from the database based on a selection.
For example: in the table, I select 323i. On a new page, I need to display all the information that's in the database about the 323i on a new page.
Is that doable and if so, could anyone please assist me in this matter.
Thank you very much in advance.
You are not using given ID parameter in your query:
$sql = "SELECT ... FROM Vehicle WHERE Id = Id ORDER BY Make";
you need to get $ID from user and place it into the query like:
$id = intval($_GET['id']); // assuming it is an integer
$sql = "SELECT ... FROM Vehicle WHERE Id = $id; // no need to order
I've been trying for hours to figure out how to put a link into the following text output via PHP echo(). I basically want to make the title field I'm pulling from my events table (as seen in #4 in the code below) to come back into the browser as a link instead of just text...
the original code that brings back the event title:
<?php
// 3. Perform database Query to bring list of events
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned Data
while ($row = mysql_fetch_array($result)) {
echo $row ["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
How would I go about getting that $row["eventtitle"] to appear in the browser as a link? Let's say if the link was just "eventprofile.php". This is probably an easy fix, but I've been getting a million errors with trying different things with <a href>s.
<?php
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo "".$row["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
add an anchor tag for it!!
echo "" . $row['eventtitle'] . '' . "<br />" .$row["eventdesc"]."<br/>";
And thats it.