I have been working on a database management page using PHP. Recently I finished the page, and was working on the security aspect, when I ran into a problem with my first SQL query. It was not prepared, and could have empty input. When I tried using the following code to prepare it, it gave an error.
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='?';";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
$stmt1->execute();
$result1 = $stmt1->get_result();
$stmt1->close();
As I understand, it was because it was not recognising the '?' as a place for parameter binding.
I then tried the following code:
if(isset($_GET["barcode"])) {
$barcode = $_GET["barcode"];
}else{
$barcode = "";
}
# array definition using $barcode
if(isset($_GET["barcode"])) {
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode=?;";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
}else{
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='';";
$stmt1 = $conn->prepare($id_query);
}
$stmt1->execute();
$result1 = $stmt1->get_result();
$stmt1->close();
$result1 = mysqli_fetch_assoc($result1);
And the page just doesn't load.
I am using a Xampp localhost Apache and MySQL server.
If I don't use the last line, $result1 = mysqli_fetch_assoc($result1);, it fails on the line after, as it can't interpret a mysqli_result as an array. (The next line is a while loop, not shown here, as it's irrelevant)
I have thought about just adding some checks (the only thing that is passed in is an EAN13 barcode, and using normal
$result1 = mysqli_query($conn, $id_query);
$result1 = mysqli_fetch_assoc($result1);
but would prefer to use prepared statements.
Note: If I print_r() the $result1 before using the mysqli_fetch_assoc() on it, I get ~960 rows. It worked fine and fast before I tried preparing the statement.
Minimal reproducible example as requested:
<form action="dash.php" method="get">
Barcode: <input type="text" name="barcode">
<input type="submit">
</form>
<?php # Gets info about the product
$conn = mysqli_connect($hostname, $username, $password, $database);
if(isset($_GET["barcode"])) {
$barcode = $_GET["barcode"];
}else{
$barcode = "";
}
if(isset($_GET["barcode"])) {
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode=?;";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
}else{
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='';";
$stmt1 = $conn->prepare($id_query);
}
$stmt1->execute();
$result1 = $stmt1->get_result();
$result1 = mysqli_fetch_assoc($result1);
var_dump($result1);
$stmt1->close();
I have figured it out. It was me being a little stupid and using a bunch of while loops where they ended up not being needed. The page wasn't loading because it was executing infinite while loops. Special thanks to Dharman and Barmar for giving me ideas.
Related
For some reason this php code on execution is returning NULL...cud any1 kindly help in correcting it?
public function like($pid)
{
$uid = escape($_SESSION['user']);
$sql = $this->_db->prepare("UPDATE postsinitial SET likes = likes+1 WHERE pid = :m;INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (:k, :m)");
$sql->bindValue(':k', $uid);
$sql->bindValue(':m', $pid);
$sql->execute();
$query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
$query->bindParam(':n', $pid);
$query->execute();
while($rows = $query->fetch())
{
return $rows['likes'];
}
}
But when i run the two parts of the query separately, i.e., commenting out the $sql batch of code and running $query batch alone, it works and returns a value.. , it works fine..but not combined as stated..so how do i run it as is?
I've tried this model too for the select query bt still same result:
$query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
$query->bindParam(':n', $pid);
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC))
{
return $rows[0]['likes'];
}
The answer is simple:
You should run your queries one by one instead of stuffing them all into a single call. Run your insert query separated rom update and you'll be fine.
public function like($pid)
{
$sql = "UPDATE postsinitial SET likes = likes+1 WHERE pid = ?";
$this->_db->prepare($sql)->execute($_SESSION['user']);
$sql = "INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (?, ?)";
$this->_db->prepare($sql)->execute([$_SESSION['user'], $pid]);
$stmt = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = ?");
$stmt->execute([$pid]);
return $stmt->fetchColumn();
}
I need to fetch the id of the last inserted row from a mysql table using php and use that id to enter a new entry on another table. I have this until now
$inductionmethod = $_POST['inductionmethod'];
$injectionmethod = $_POST['injectionmethod'];
$dosage = $_POST['dosage'];
$metric = $_POST['metric'];
$notes = $_POST['notes'];
global $db_usr;
$query = "SELECT MAX( experiment_id ) FROM experiment";
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
$query ="INSERT INTO experiment_using_methods (experiment_id, induction_method, injection_method, dosage_quantity, dosage_unit, dosage_qualitative)
VALUES (
'".$lastid['MAX( experiment_id )']."', # the fetched ID of the corresponding dataset
(SELECT induction_method_id FROM induction_method WHERE im_name = '".$inductionmethod."'), # name of induction method
(SELECT injection_method_id FROM injection_method WHERE im_name = '".$injectionmethod."'), # name of the injection method
'".floatval($dosage)."', # dosage quantity
'".$metric."', # dosage unit or metric
'".$notes."' # qualitative dosage - REMOVE??
)";
$prep = $db_usr->prepare($query);
$prep->execute();
I think I'm getting an error while fetching the MAX( experiment_id) or maybe I'm using it incorrectly on the INSERT statement because if I replace the ".$lastid['MAX( experiment_id )']." part by a number the insert statement works fine. On the other hand I also test the SELECT MAX( experiment_id ) FROM experiment statement on the mysql command line and it also works fine. Am I using fetch and referencing the result value correctly?
Thing this is the main issue:
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
change it to:
$prep = $db_usr->prepare($query);
$prep->execute();
$lastid = $prep->fetch();
If you have connection as $con, then for MySQLi Object-oriented:
if ($con->query($sql) === TRUE) {
$last_id = $conn->insert_id;
}
MySQLi Procedural way:
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
}
PDO way:
$con->exec($sql);
$last_id = $con->lastInsertId();
I'm new to PDO, I'm using it as advised by senior users in this website.
I'm trying to get data from my table using pdo, using while, so I can get all the data "organized".
My query is working, but for some reason I can't even dump it.
Heres my code:
$sql = $conn->query("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
while($row = $conn->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main'){
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}else{
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
}
So, in a resume.
I have a table with titles, some text and an id.
I want to get this data from it and echo it.
Hope you can help me, sorry for the newb doubt.
EDIT 1:
$username = 'sssss';
$password = 'sssss';
$conn = new PDO('mysql:host=xxxxxxxx;dbname=account', $username, $password);
$sql = "SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC";
$stmt = $conn->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '<li><font color="green">Nivel '.$row['nivel'].' - '.$row['titulo'].'</font></li><br>';
}else{
echo '<li><font color="red">Nivel '.$row['nivel'].' - '.$row['titulo'].'</font></li><br>';
}
}
Well, advise you were given is wrong.
Not use but learn.
You have to learn something before using it.
There are many tutorials on PDO around (all of them crappy ones though) but at least you can learn proper syntax from there
$sql = "SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC";
// look this string contains SQL query. so, the variable is named $sql
$stmt = $conn->query($sql);
// in the next line we are getting a statement object from the function query()
// this is why variable called $stmt
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// and now we can start iterating this statement.
// statement, Carl. Not connection to database
// which is called $conn, if you get an idea
also you have to enable error reporting for PDO.
And yes, as it was said in the other answer, your PHP syntax is also wrong. You are supposed to learn it too, instead of banging together random lines of code and then asking others to fix it for you.
Start from less complex syntax, from echoing one single variable without decoration. And ask one question per post. As for the PDO part you already got the answer
Try using a foreach loop. Once the loop is finished you can actually use the $arrRows array anywhere throughout the file! I was told by one of the senior web developers that this is a better way to do it.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $key => $arrRows){
echo $arrRows['COLLUMN_NAME_HERE'];
}
Here is a demo function that will select values from a table using PDO
function showPost($uID){
global $numRecords, $dbConnection, $stmt;
connect(); //Run connect function (../connections/connections.php)
$sqlStr = "SELECT user_post.*, user.name, user.avatar FROM user_post JOIN user ON user_post.uID = user.uID WHERE user_post.uID = ".$uID. " ORDER BY post_time DESC";
//Run Query
try
{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false)
{
die("Error executing the query: $sqlStr");
}
}
catch(PDOException $error)
{
//Display error message if applicable
echo "An error occured: ".$error->getMessage();
}
$numRecords = $stmt->rowcount();
//Close the databaase connection
$dbConnection = NULL;
}
Let me know if you have anymore questions
You were using your connection variable conn instead of your query variable sql to fetch your query results.
$sql = $conn->query("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main')
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
else
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
Or you can do similarly using Prepared Statements
$sql = $conn->prepare("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main')
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
else
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
My goal is to recieve 2 strings, an IP and UUID, and look in the database. If the UUID is already there, it adds the IP onto a list of IPs in the database. If not, it makes a new row in the database with that UUID and IP. Purpose is tracking user activity (Nothing malicious)
Code:
<?php
$cip = $_POST['ipaddr'];
$cid = $_POST['id'];
$conn = mysqli_connect('localhost', '*****', '*****', '*****');
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
if(mysqli_num_rows($query) > 0){
$sql = "SELECT asid, ips FROM sls WHERE asid=$cid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$cipdata = $row["ips"];
}
$sql = "UPDATE sls SET ips='$cipdata , $cip' WHERE id=2";
mysqli_query($conn, $sql);
} else {
$sql = "INSERT INTO sls (asid, ips) VALUES ('$cid', '$cip')";
mysqli_query($conn, $sql);
}
?>
Right now, it just adds a new row for every IP, regardless of UUID.
What did I do wrong?
-- Edit: Fixed typo, now it just adds the first IP, but after that does not add any more to the row.
Perhaps there is a small typo on this line:
$query = mysqli_query($con, "SELECT * FROM sls WHERE asid='".$cid."'");
Did you mean $conn, not $con? As in:
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
Your connection param is $conn so just used this in every query command. some where you are using $con and somewhere $conn.
Check your code.
I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}