I have code that adds an array to a session like this:
array_push($_SESSION['cart']['1'] = 3);
array_push($_SESSION['cart']['18'] = 1);
This would add item id "1" with quantity "3" and add item id "18" with quantity "1". I want to show these items from database on cart page.
I'm not good in php or sql, but something like:
while (list ($id, $quantity) = each ($_SESSION['cart'])) {
$results = $conn->query("SELECT * FROM products ORDER BY id ASC");
}
and do something like find $id(from session) = $id(from database) so I could show session as information from database. With item name, item desc., item price, and quantity.
Here is a quick example highlighting what u're trying to retrieve (id_item) from $_SESSION :
http://www.tehplayground.com/#Iyf7c0LTM
$arr = array();
$arr['cart']['1'] = 3;
$arr['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
foreach($arr['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
U can use now make ur sql query :
$sql = "SELECT * FROM products WHERE id =". $row;
EDIT - Since it was unclear for you, I made u the direct answer :
<?php
session_start();
// Examples of shopped items (added to $_SESSION['cart'])
$_SESSION['cart']['1'] = 3;
$_SESSION['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
// Further informations how foreach works with array
// https://stackoverflow.com/questions/10057671/how-foreach-actually-works
foreach($_SESSION['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
// Full Display to help understanding the process
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
Advanced explanations about "how foreach interacts with array" : here
EDIT 2 :
Fill db variables + column names of your table
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$mysqli = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Query the DB - Get itemID & quantity added in the cart table
$query = "SELECT itemID, itemQuantity FROM cart";
$result = $mysqli->query($query);
// Return the result into an array
$res_array = $result->fetch_array();
// Add the items into $_SESSION
// Pattern : $_SESSION['cart']['$itemId'] = $itemQuantity
foreach($res_array as $row)
$_SESSION['cart'][($row['itemID'])] = $row['itemQuantity']
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
Example : here
Rather than getting everything from the database and then comparing in php you can do something like this to only get the records that you need:
"SELECT * FROM products WHERE id IN(1,18) ORDER BY id ASC"
The PHP might be as simple as: $in = implode(",", $_SESSION['cart']); although you should also make sure to protect against SQL injection.
Related
I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]
Please see the below code.
I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.
Does anyone know please how I can get them into two separate variables instead?
Thanks!
//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}
//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');
//Process the results
if (mysqli_num_rows($result) > 0) {
while ( $dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
}
Change :
while ($dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
To this :
$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
$values[] = $dataValue['element_value'];
}
print_r($values);
This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.
If you want to display them in an array again, you can do this :
foreach ($values as $value)
{
echo "<p>".$value."</p>";
}
I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649
Just trying to pass a variable on URL so that when echoed I can click on it and open it's own content based on the database record. Right now this one shows all the records from database but what I was trying to do was pass a URL so each blog IDs will have it's own URL and when clicked on it will open the individual entries rather than all the entries.
Edited Now I'm able to show rows of entries with IDs where 'IDs' has URL variable at the end. Do I need to create another query to echo the individual entry on my mini blog?
<?
$db = // connection to db and authentication to connecting to db;
#$postID = $_GET['postID']; // I'm thinking to use a $_GET global variable to work with URL variable
$command = "select * from $table_name"; // I'm thinking to add the Id here or something or create another query to echo the linked URL 'viewblog.php?postID=$data->blogID'
$result = $db->query($command);
while ($data = $result->fetch_object()) {
echo "<TR><TD><a href='viewblog.php?postID=$data->blogID'>".$data->blogID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
$db->close;
Why this script is giving all entries?
Because the final query that is being sent to the database is something like
select * from TABLE_NAME
which will return all entries since your are using the asterix * after SELECT
What you are asking for can be obtained if the executed final query contains the "blogID" before retrieving the results and start fetching them.
http://www.w3schools.com/sql/sql_where.asp
You should also use the fetched or post ID in the echoed result (so that when clicked, each blog has its own id in the link).
It could be something like this
$postID = $_GET['postID'];
//Add filtering by id to select statement
$command = "select * from '$table_name' obj WHERE obj.blogID = '$postID'";
$result = $db->query($command);
while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
//Add ID to echoed link
echo "<TR><TD> Some Blog (ID: ".$data['blogID'].") </TD>";
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."</TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
}
WATCH OUT for security issues regarding this code. You should use a safer way to do this. I'm only explaining the results.
As for Auto Increment, it can be initiated when you first created the table. This is for when you INSERT a new row into the database. When you use Auto Increment, you don't have to give an ID manually.
http://www.w3schools.com/sql/sql_autoincrement.asp
Notice : The HTML BR ELEMENT should not be used inside TABLE structures.
Hope it helps.
You could create some function like this for returning single post based on url
function single_blog($Post_id){
$sql = "SELECT * FROM your_table WHERE post_id = ? LIMIT 1";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($Post_id);
return $stmt->fetch();
}
You are selecting all entries from your table. Use the following:
$db = // connection to db and authentication to connecting to db;
$postID = $_GET['postID']; // ??
$db->real_escape_string(trim($postID));
$command = "select * from $table_name WHERE `postID`=$postID";
$result = $db->query($command);
// Ensure results before outputting
if ($result->num_rows) while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
echo "<TR><TD><a href='viewblog.php?postID='>".$data['blogID']."</a> </TD>"; //??
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."<BR></TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
} else echo "No entry found!";
$result->free();
$db->close;
<?php
//$db connect to database
// Entry form sanitation of $_POST
// Insert PHP file to MySQL
// View all blog posts
$postID = $_GET['postID']; // I guess I should sanitize this as well
if (!empty($postID)) {
$command = "select * from $table_name where blogID = $postID";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD>".$postID."</TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
else {
$command = "select * from $table_name";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD><a href='viewblog.php?postID=$postID'>".$postID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
$db->close;
?>
I took my old mysql script and attempted to convert it to a more secure PDO format. In my old script I ran a SELECT field FROM table statement then put it into a variable
$Product = $row['product']; and run an IF and ELSE statement. If the users product = sony I wanted to echo " you may be interested in these as well" Here is my example code below
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("dbname");
$username = $_SESSION['username'];
$q = "SELECT product FROM users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Product = $row['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
Now with the PDO-Statement, it seems you can not run the same sort of statement as before as easiliy. I tried assigning a variable to the row product that my query is selecting from but I get the error:
Cannot use object of type PDOStatement as array
Here is my code
<?php
session_start();
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$getProduct = $db->query("SELECT product FROM users WHERE username = '$username'");
$getProduct->execute();
$Product = $getProduct['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
How can I pass the field "product" from the table I am selecting from to a variable with PDO and IF the product ="sony" echo "message"; ?
I also tried replacing the statements with this too with no success.
<?php
$query = $db->query("SELECT product FROM users WHERE username = '$username'");
$query->execute();
$Product = $query ->fetchAll(PDO::FETCH_ASSOC);
$Product = $getProduct['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
The manual is not very friendly in regards to converting old statements to newer and secure ones, so I appreciate any direction on this, thank you.
use
$query->fetch(PDO::FETCH_ASSOC);
to get 1 row and
$query->fetchAll(PDO::FETCH_ASSOC);
to get all rows
You are expecting one row so use the first one.
The other page that is the index page shows the catalog of the pizzashop. Each pizza is a hyperlink that passes the id to this page.
The core of my question is in the code that starts with the foreach loop. I would like to simply read out of the database based on the SELECT query at hand.
I know it is weird to put the query IN the loop but for now it is the only way I figured out how to loop through all the ids that are in the SESSION array.
I tried many things to output the return that the query is supposed to give, I fiddled around with the mysqli_stmt thing, all giving me numerous types of errors.
<?php
session_start();
require 'pizza_sc_fns.php';
require 'header.php';
#$pizzaId = $_GET['pizza_id'];
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
$_SESSION['items'] = 0;
$_SESSION['totalprice'] = 0.00;
}
if (isset ($_SESSION['order'][$pizzaId]))
{
echo $_SESSION['order'][$pizzaId]++;
echo "\$_SESSION['order'][\$pizzaId] is SET \n";
}
else
{
echo $_SESSION['order'][$pizzaId] = 1;
}
$conn = connect2db();
foreach ($_SESSION['order'] as $pizzaItem)
{
$query = "SELECT pizza_name FROM pizzas WHERE pizza_id = $pizzaItem";
$res = #$conn->query($query);
echo $res->fetch_assoc();
echo "<hr />";
//$query = mysqli_prepare($conn, "SELECT * FROM pizzas WHERE pizza_id=$pizzaItem");
//echo var_dump($query)."<br />";
//$stmt_exec = mysqli_stmt_fetch($query);
//print $pizzaItem."<br />";
}
?>
Destroy session >>
You are going to need to use a loop but you don't need to run the query for every iteration. You can use the in clause.
Your code would be something like
$query = 'Select pizza_name from pizzas where id in (';
foreach($_SESSION['order'] as $pizza_id) {
$query.= mysql_real_escape_string($pizza_id).', ';
}
$query= substr($query, 0, -2); //Get rid of the trailing comma and space
$query .= ')';
And you can run the query.
I would recommend that you use prepared statements though I'm not sure how to use them for an in statement.