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.
Related
I want to fetch data from the database and use the first row initially. Then later if some values are true I want to loop through all of the rows.
The problem is that the while loop starts at the second row.
Is there a way to make the loop start at the first row?
Below is simplified example:
<?php
//GET THE CONNECTION DATA FOR $CONNECTION
require_once('../connect.php');
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
while($data = $get_data->fetch())
{
//STARTS AT THE SECOND ROW BUT NEEDS TO BE THE FIRST ROW
echo $data->last_name;
echo '<br>';
}
Yes you can use fetchAll()
$results = $get_data->fetchAll ();
$data = $results[0];
echo $data->email;
echo '<br>';
foreach($results as $data) {
//...
}
If you need something like this, you are doing something wrong.
For the question stated in the title, Dharman's answer is correct and should be accepted for sake of future visitors.
However, in your particular case, you don't need the first fetch and most likely don't need a while loop.
The first fetch is not needed because it is used to output the data you already have (the email used to query the database).
The while loop is not needed because most likely there is only one record in the database with such email, so you can just echo the username right away.
Either way, a sane version of your code would be either
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
echo $data->last_name;
echo '<br>';
or (in case your query indeed returns multiple rows)
$email = 'john#doe.com';
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => $email]);
echo $email;
echo '<br>';
while($data = $get_data->fetch())
{
echo $data->last_name;
echo '<br>';
}
See - you never need to "restart" the while loop.
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.
Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc
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 looked for an answer prior to writing this but found nothing, but feel free to post a link if I missed it.
I am trying to get the values from a single row of my mysql table. The query I'm using below returns nothing; the echo of mysql_num_rows is always zero. I know the title variable used in WHERE is valid and the database is connected, etc.. Thanks in advanced.
$title = $_REQUEST["title"];
$query = mysql_query("SELECT * FROM links WHERE title = '$title'");
if(!$query) {
die ("Error: " . mysql_error());
}
echo mysql_num_rows($query);
$row = mysql_fetch_row($query);//also tried mysql_fetch_array
$link = $row['link'];
$type = $row['type'];
$user = $row['user'];
$date = $row['date'];
$rating = $row['rating'];
$info = $row['info'];
Try with:
$title = mysql_real_escape_string($_REQUEST["title"]);
$query = mysql_query("SELECT * FROM links WHERE title LIKE '$title'");
echo $query // run it in mysql prompt to check if there are any results first.
if(!$query) {
die ("Error: " . mysql_error());
}
echo mysql_num_rows($query);
$row = mysql_fetch_row($query);//also tried mysql_fetch_array
$link = $row['link'];
$type = $row['type'];
$user = $row['user'];
$date = $row['date'];
$rating = $row['rating'];
$info = $row['info'];
$title = $_REQUEST["title"];
$query = mysql_query("SELECT * FROM links WHERE title = '$title'");
if(!$query) {
die ("Error: " . mysql_error());
}
echo mysql_num_rows($query);
while($row = mysql_fetch_row($query))
{
$link = $row['link'];
$type = $row['type'];
$user = $row['user'];
$date = $row['date'];
$rating = $row['rating'];
$info = $row['info'];
}
If mysql_num_rows returns zero it means that your query is probably not selecting anything from the database. You have to check if your sql query is actualy selecting anything. Check the value of the $title variable and try excecuting the query directly to your database.
You are also vulnerable to sql injections. Always filter user input. You can use mysql_real_escape_string and htmlspecialchars for that.
Try getting values without a where just like this one:
$query = mysql_query("SELECT * FROM links") or die(mysql_error());
If there is wrong it should prompt you the error.
Many people are already saying it but try to cleanse the request parameters ^_^
One common thing to do is print out your sql query to make sure its what you expect.
$sqlquery = "SELECT * FROM links WHERE title='".$title."'";
$query = mysql_query($sqlquery);
echo $sqlquery;
also, as has already been mentioned... you're vulnerable to SQL Injection attacks.
you should use
while($row = mysql_fetch_row($query){...} and also use mysql_real_escape_string to avoid sql injection. And also dont use echo command infront of mysql_num_rows. And even i think its not necessary to get number of rows to execute the remaining part of the script.
P.s i'm on mobile so i'm not able to post script.