I wanted to make an automatic table display all the products from the database, where you can click on its name and view the whole details of the product. And my idea was that it wouldn't bring you to another .php file, but rather you'll still be on the same page so you wouldn't waste time on creating multiple .php files of every products.
The problem is, whenever I click on a product, it wouldn't load the product's information (the only detail is the description by the way).
Error
Fatal error: Cannot use object of type mysqli_result as array in C:\wamp\www\goldenrod\index.php on line 56
This is the database connection:
<?php
//Database Connections
$dbc = mysqli_connect('localhost', 'root', '', 'lionsierra_db') or die("Cannot find specified server");
//Product Database
$db_products = "SELECT * FROM `products`";
$products = mysqli_query($dbc, $db_products);
?>
And this is the function:
<?php
//View product
if(isset($_GET['view_product'])) {
while($product=mysqli_fetch_assoc($products)) {
$products['ID'] = $_GET['view_product'];
//Display a product
echo "<p><span>
<span style='font-weight:bold;'>" . $products['ID']['name'] . "</span><br/>
<span>$" . $products['ID']['price'] . "</span><br/>
<span>" . $products['ID']['category'] . "</span><br/>
<span>" . $products['ID']['description'] . "</span>
</p>";
}
}
//View all products
echo '<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
</tr>';
while($product=mysqli_fetch_assoc($products)) {
echo "<tr>
<td><a href='./index.php?view_product=" . $product['ID'] . "'>". $product['name'] . "</a></td>
<td>" . $product['price'] . "</td>
<td>" . $product['category'] . "</td>
</tr>";
$ID = $product['ID'];
}
?>
I'm still fairly new to PHP and SQL, and it would be grateful if you guys could help me out.
The issue resides here:
if(isset($_GET['view_product'])) {
while($product=mysqli_fetch_assoc($products)) {
Looks like you're just re-using a MySQLI query here. Instead, you should be altering the query depending on the productID. Let's see what that looks like:
if(isset($_GET['view_product'])) {
//now let's build out our query
$view_product_statement = mysqli_prepare($conn, "SELECT * FROM products WHERE ID = ?");
mysqli_stmt_bind_param($view_product_statement, 'i', $_GET['view_product']);
mysqli_stmt_execute($view_product_statement);
mysqli_stmt_bind_result($view_product_statement);
while($product=mysqli_fetch_assoc($view_product_statement)){
//now $product holds reference to the one we're trying to view.
}
mysqli_stmt_close($view_product_statement);
}
I've used prepared statements in my above to help sanitize your user input in such a way that you help avoid SQL Injection.
Related
I am passing over a factory operations system to a new support team and I am writing a guide for that.
It has a VERY simple DB section tucked inside and I just want very basic set of procedures for demonstration to the team who are very IT literate but do not have any DB or PHP experience.
I have finished most of the guide but having a bit of a problem with a simple Quantity update procedure.
Be clear - I have no problem doing it but I have searched and searched for a simple answer and also everything I do seems just far more complex than it needs be. Can anyone assist with simplicity !
As the base exampler I am using the well tried
<?php
$con=mysqli_connect('localhost', 'bbbbbb', 'bbbbb', 'bbbbbbl') or die(mysql_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM orders_products");
echo "<table border='1'>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Quantity</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['products_id'] . "</td>";
echo "<td>" . $row['products_name'] . "</td>";
echo "<td>" . $row['products_quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
which gives a simple table at the level I need
NOW all I want to demonstrate is how to update some or all of the Product Quantities in the list back to the MYSQL database. BUT AS SIMPLY AS POSSIBLE Without using individual "Edits" for each row. Apologies if this is too low level for you chaps !
NOTE: Edited to improve secrurity, but this does NOT negate the need for prepared statements to prevent other SQL injection attacks.
Wrap
<form method='POST' action='?'> around the table.
Replace
echo "<td>" . $row['products_quantity'] . "</td>";
With
$iProctId = $row['products_id'];
$iQuantity = $row['products_quantity'];
echo "<td>";
echo "<input type='text' name='product[{$iProductId}]' value='{$iQuantity}'/>";
echo "</td>";
In your script:
foreach( $_POST['product'] as $iProductId => $iQuantity ) {
mysqli_query( $con,"
UPDATE
orders_products
SET
products_quantity = ".(int)$iQuantity."
WHERE
products_id = ".(int)$iProductId."
");
}
Disclaimer
This script is simple, but not safe! To get it safe: mysqli_real_escape_string and mysqli_prepare
Enjoy :)
I have a page that I have been working on. It runs several queries to get existing data from several tables in my DB. There is a table that shows the result of three queries. The first query gets the extension and the secret of phones, the 2nd query gets MAC addresses of phones, and finally the third query gets the names of templates for the phones. The results of the last two queries (with the help of others) are setup as dropdowns in the 3rd and 4th columns of the table created to show the extensions. This way I can select the MAC of the phone I want to assign to the extension and then the template to make the phone work the way I want. The whole page is set as a form and I am using $post to the insert page. My goal here is to take the information (array) that is created by the user making their selections and insert ALL the 4 columns of information into a new table, from there I want to create files using that information to setup the phones. Here is the code I have for now.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$link = mysql_connect("localhost", "root", "cacti") or die ('Error connecting to mysql' . mysql_error());
mysql_select_db("cqadmin");
$sql2 = "SELECT extension, secret from extensions;";
$result2 = mysql_query($sql2) or die(mysql_error());
echo "<table border='3'>
<tr>
<th>Extension #</th>
<th>Secret</th>
<th>MAC Address</th>
<th>Template</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
$sql = "SELECT id , mac FROM phones order by mac;";
$result = mysql_query($sql) or die(mysql_error());
$sql1 = "SELECT id , templatename FROM templates order by templatename;";
$result1 = mysql_query($sql1) or die(mysql_error());
echo "<tr>";
echo "<td>" . $row['extension'] . "</td>";
echo "<td>" . $row['secret'] . "</td>";
echo "<td> <select name='phone'>";
while($rowA = mysql_fetch_array($result)) {
echo '<option value="' . $rowA['id'] . '">' . $rowA['mac'] . '</option>';
}
echo "</select></td>";
echo "<td><select name='template'>";
while($rowB = mysql_fetch_array($result1)) {
echo '<option value="' . $rowB['id'] . '">' . $rowB['templatename'] . '</option>';
}
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" value="Submit your selections">
</body>
</html>
And my insert page
<?php
echo "You got here";
//***********Get the Assignment information *************
$values = array_values($_POST);
print_r($values);
?>
The resulting print shows this
Array ( [0] => 324 [1] => 24 )
Looking at my db table 324 is the index id of the last phone scanned and in the template table 24 is the last template created, No info on the extension or the secret.
I think I am close but I do not know where to go from here.
PS. I know I need to use mysqli or pdo, not sure how to change over yet.
I'm able to display what I have in my table with the code below, but as you can see in the code I'm linking the rows to a new page, and on that page I'm trying to display the rest of the rows, which I have in the same table.
I mean, I have cols ID, photo, Firstname, Lastname, Age, StreetAdd, PhoneNum, EmailAdd in the table. I'm displaying only rows photo, Firstname, Lastname on the first page.
So what I'm trying to do is when the user clicks on the First name , which I displayed from the database, he will be redirected to the new page and see the rest of the info. How do I do it?
This is the PHP page which displays the three cols. I can display the rest of the cols on a new page but it's displaying all the info in the row. I want to display the individual info for each user, not the whole list. A possible example would be eBay. When you search for items, you won't see the full description until you click on the picture or the title.
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$result = mysql_query("SELECT * FROM test ");
echo "<table align='center' bgcolor='#F9F0F0' border='0' cellspacing='0'>
<tr>
<th><font color='red'>Firstname</font></th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td><a href='send.php'><img src='".$row['photo']."' \" width=\"150px\" height=\"150px\" /></a><br><br><br>";
echo "<a href='send.php'><td align='center' style='vertical-align:text-top' width='200px'>" . $row['Firstname'] . "</td>";
echo "<td align='center' style='vertical-align:text-top' width='200px'>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
On you have put a text level element a inside a block level element td the cell where first name is shown. Also you didn't close a tag there. correct form is this.
echo "<td align='center' style='vertical-align:text-top' width='200px'>";
echo "<a href='send.php'>" . $row['Firstname'] . "</a></td>";
To get the same user bio on the send.php you need to pass the primary key for this row. For examle if the primary key is id you pass it send.php in query string.
echo "<a href='send.php?id=".$row['id']."'>" . $row['Firstname'] . "</a></td>";
Now in the send.php use $_GET['id'] to get the primary key and use it to retrieve the user bio from db.
But make sure you escape parameters you pass to sql database. Dont use those variables directly! See Nullpointer's answer
Update 1:
When you get the primary key of a row just invoke a SELECT * with LIMIT 1
$pkey = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM test where id='$pkey' LIMIT 1";
/* Run this sql */
to display individual info for each user you can use where close in query like
SELECT * FROM test WHERE user = bla
Warning
your code is vulnerable to sql injection you need to escape all get and post and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
Pdo Tutorial For Beginners
This should be your first page
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$result = mysql_query("SELECT * FROM test ");
echo "<table align='center' bgcolor='#F9F0F0' border='0' cellspacing='0'>
<tr>
<th><font color='red'>Firstname</font></th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td><a href='send.php'><img src='".$row['photo']."' \" width=\"150px\" height=\"150px\" /></a><br><br><br>";
echo "<a href='send.php?".$row['id']."'><td align='center' style='vertical-align:text-top' width='200px'>" . $row['Firstname'] . "</td>";
echo "<td align='center' style='vertical-align:text-top' width='200px'>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Now send.php should be
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$sql = "SELECT * FROM test where id = " . $_Get['id'] ;
$result = mysql_query($sql);
//then display the result here
?>
hope this helps
I have an upload system in my site where users can upload files and write a brief description of them. Each upload has a corresponding SQL entry.
Another page on my site will then display every file uploaded along with some traits about that file
The question is:
How can create a table with a variable set of rows and how can I set a table to automatically populate the new rows?
I am capable with PHP but still a novice, weak with HTML (I use a wysiwyg) and completely inexperienced with Javascript.
Any nudge in the correct direction would be hugely appreciated...
In order to make the rows of your HTML table "dynamic" using PHP, you should use the foreach() control structure. For example, say you have some code to grab the data from the database and it returns it as an array or some sort of result statement that implements an Iterable interface (we'll call it $results), you can then:
<table>
<thead>
<tr>
<th>File Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
foreach($results as $result)
{
// Start row
echo("<tr>");
echo("<td>" . $result->filename . "</td>");
echo("<td>" . $result->description . "</td>");
// End row
echo("</tr>");
}
?>
</tbody>
</table>
You can use a loop to populate the table based on results from a query of your database. Here's the code I use for one of my pages:
$result = $db->query_read("SELECT dice.RollID AS `Roll`, dice.Limit AS `Limit`,
dice.Value AS `Value`, dice.Dateline AS `Dateline`, dice.Comment AS `Comment`
FROM dice
ORDER BY Dateline DESC LIMIT 25");
// ###### MAIN CODE ######
$str = '<table>
<tr><th>ID</th><th>Roll</th><th>Time</th><th>Comment</th></tr>';
while ($resultLoop = $db->fetch_array($result)) {
$ID = $resultLoop["Roll"];
$roll = $resultLoop["Value"] . '/' . $resultLoop["Limit"];
$when = date('m-d-Y H:i:s', $resultLoop["Dateline"]);
$comment = $resultLoop["Comment"];
$str .= '<tr>
<td>' . $ID . '</td>
<td>' . $roll . '</td>
<td>' . $when . '</td>
<td>' . $comment . '</td></tr>';
}
$str .= '</table>';
echo $str;
One thing to note is that I use $db->* functions because it is integrated with a forum software. You should be using mysqli_* functions as found here: http://php.net/manual/en/book.mysqli.php
Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/