Php PDO, Insert a changable varible - php

TEST WEBSITE: csgodice.co.uk
I've been looking into PDO, but it confuses me, i am only 14 and im not that knowledge about mysql in php all i know is to use PDO and some parts of databases, i was wondering how i would insert a changable value, such as balance, here is my information i want to insert into my table as rows
$conn->prepare("INSERT INTO users (64ID, BALANCE, AMOUNTBET) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $64id, $balance, $amountbet );
// set parameters and execute
$_64id = "$steamprofile['steamid']";
$balance = "";
$amountbet = "";
$stmt->execute();
I Have connected to my mysql so all that is done, all i really need to know is how to insert rows? i know there is documentation about it but the topics on there differ to what i am trying to do?

Take from PHP documentation http://php.net/manual/en/pdostatement.bindparam.php
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
so your code will be:
$stmt = $conn->prepare("INSERT INTO users (64ID, BALANCE, AMOUNTBET) VALUES (:_64id, :balance, :amountbet)");
$_64id = $steamprofile['steamid'];
$balance = "";
$amountbet = "";
$stmt->bind_param(:_64id, $_64id);
$stmt->bind_param(:balance, $balance);
$stmt->bind_param(:amountbet, $amountbet);
$stmt->execute();

Related

Since I'm changing mysqli queries to PDO prepared statements, can I eliminate all escaping?

I'm giving in to "doing the right thing" and going to change all my mysqli queries to use PDO so I was hoping someone could confirm I'm doing it correctly. Here is an old one:
$sql = "INSERT into profile (profileid, name, description) values ('$profileid', '$name', '$description')";
$sql= mysqli_query($connection,$sql);
if (!$sql) {
die("Database query failed: " . mysqli_error($connection));
} else {
redirect_to('/my-account');
}
And here is how I rewrote it:
$stmt = $pdo->prepare("INSERT into pools (profileid, name, description) values (:profileid, :name, :description)");
$stmt->execute([':profileid' => $profileid, ':name' => $name, ':poolname' => $poolname, ':description' => $description]);
redirect_to('/my-pools');
It seemed to work fine when I tested, just want to make sure I did EVERYTHING right. Does it all look good?
Also, and I guess my main question, prior to my old mysqli query, I would do this to "sanitize" the data:
$description = mysqli_real_escape_string($connection,$_POST['description']);
With PDO, I do NOT have to have that AT ALL anymore, as long as I'm using placeholders in the statement, correct? Hoping to confirm before I delete all the escaping stuff from my code after switching to PDO.
It will work but you just bound all your parameter as string which is the default behaviour if you pass the bounded values to the execute method.
If you need more control or want to be more specific about the type of the parameter your should use bindValue and bindParam and pass one of PDO predefined constants:
PDO::PARAM_BOOL
PDO::PARAM_NULL
PDO::PARAM_INT
PDO::PARAM_STR
PDO::PARAM_LOB
PDO::PARAM_STMT
PDO::PARAM_INPUT_OUTPUT
Example from the docs:
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
See the following answer to understand the differences between bindValue and bindParam:
What is the difference between bindParam and bindValue?

Fatal error: Call to a member function bindParam() on a non-object

This code is used to login using authentication , session management. error comes in 15th line of code which is fatal error: call to a member function bindParam() on non-object. i am not understanding that where is the mistake done by me. please help me.
<?php
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$pwd= md5($password);
// Connect to the MySQL server
$db = new mysqli("localhost", "root", "", "login");
// Determine whether an account exists matching this username and password
$stmt = $db->prepare("SELECT id FROM accounts WHERE username =$username and password =$pwd");
// Bind the input parameters to the prepared statement
// the error comes in this line
$stmt->bindParam('ss', $username, $pwd);
// Execute the query
$stmt->execute();
// Store the result so we `enter code here`can determine how many rows have been returned
$stmt->store_result();
if ($stmt->num_rows == 1) {
// Bind the returned user ID to the $id variable
$stmt->bind_result($id);
$stmt->fetch();
// Update the account's last_login column
$stmt = $db->prepare("UPDATE accounts SET last_login = NOW() WHERE id=$id");
$stmt->bind_param('d', $id);
$stmt->execute();
$_SESSION['username'] = $username;
// Redirect the user to the home page
header('Location: home.php');
}
?>
$stmt = $db->prepare("SELECT id FROM accounts WHERE username =$username and password=$pwd");
$stmt->bindParam('ss', $username, $pwd);
You're binding a parameter that does not exist. You're also trying to bind two parameters with a single call.
Docs for the relevant function
Sample (taken from php.net) :
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
[edit]
Looks like this was actually about mysqli. Relevant doc
Relevant sample:
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

Am I supposed to use PHP PDO in an OOP way?

Im new to PDO, heard that this is the better method to do web applications, and im developing small billing application.
Having one dobut, can i do coding like below?
<?php
require_once '../../classes/PDO_connection.php';
$type = 'initial_stock';
$item_code = $_POST["item_code"];
$category = $_POST["category"];
$variety = $_POST["variety"];
$quantity = $_POST["quantity"];
$price = $_POST["price"];
$f_price = number_format($price, '2', '.', '');
$total = $quantity * $price;
$full_name = $item_code.':'.$category.':'.$variety.':'.$f_price;
$in_stock = $quantity;
$prev_stock = '';
//inserting data from initial stock page
$stmt = $pdo->prepare("INSERT INTO silk (type, item_code, category, variety, quantity, price, full_name, total, in_stock, sale_date, entered_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, now(), now())");
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $item_code);
$stmt->bindParam(3, $category);
$stmt->bindParam(4, $variety);
$stmt->bindParam(5, $quantity);
$stmt->bindParam(6, $price);
$stmt->bindParam(7, $full_name);
$stmt->bindParam(8, $total);
$stmt->bindParam(9, $in_stock);
$stmt->execute();
//getting all initial stock for dispaling
$stmt = $pdo->prepare("SELECT * FROM silk WHERE type='initial_stock'");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $stock){
echo "<tr class='active'>
<td>".$stock['item_code']."</td>
<td>".$stock['category']."</td>
<td>".$stock['variety']."</td>
<td>".$stock['price']."</td>
<td>".$stock['quantity']."</td>
<td><a id='initial_stock_silk_delete' id_to_delete=".$stock['id'].">Delete</a></td>
</tr>";
}
In mysql, i call the function that has query and return the value, but i thought PDO no need that? am i correct? expecting proffesionals advice.... thanks.
It's entirely up to you. If you want to use a function you already accustomed with - nobody forbids you from creating one.
The only thing you MUST take into account - such a function should accept at least TWO arguments - a query with placeholders and an array with data to bind

Replacing "?" in a string by values from array

I'm trying to replace every "?" in string by values from array. Each "?" is the next value from array.
I was wondering if there is a better way to do the following:
$query = 'SELECT * FROM pages WHERE id = ? AND language = ?';
$values = array('1', 'en');
foreach ($values as $value) {
$query = preg_replace('/\?/', '\''.$value.'\'', $query, 1);
}
echo '<pre>'.print_r($query, true).'</pre>';
Would like to do that with native PHP (not a PDO extension).
Use binding
in PDO
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
http://php.net/manual/pl/pdostatement.bindvalue.php
in mysqli
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
if you want to do it in STUPID way you can use loop or recursion
$select = "SELECT * FROM pages WHERE id = ? AND language = ?";
$params = array('param', 'param2');
while(preg_match('/\?/', $select)) $select = str_replace("?", array_shift($params), $select);
but it's stupid
Mysqli and PDO are as native as it gets with PHP.
You can use bind_param from mysqli to accomplish this. Example:
$stmt = $mysqli->prepare("SELECT * FROM pages WHERE id = ? AND language = ?");
$stmt->bind_param('is', 1, "en");
In this case the i and s are referencing the type of the parameter, as seen in this table (available in link):
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets

pdo statement failing to execute

i have a pdo block for inserting values into my table as follows
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$name = $_POST['name'];
$desc = $_POST['description'];
$cond = $_POST['condGroup'];
$sprice = $_POST['sprice'];
$iprice = $_POST['iprice'];
$incprice = $_POST['incprice'];
$duration = $_POST['duration'];
$img = $_POST['img'];
$owner = $_SESSION['username'];
$valid = "set";
$stmt2 = $pdo->prepare("SELECT * FROM auction WHERE ID = :id");
$stmt2->bindParam(":id", $random, PDO::PARAM_INT);
while(isset($valid)){
$random = rand(100000,999999);
$stmt2->execute();
if(!$stmt2->fetch(PDO::FETCH_ASSOC)){
unset($valid);
}
}
$timestamp = time() + ($duration * 24 * 60 * 60);
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
$stmt->bindParam(':id', $random, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':owner', $owner, PDO::PARAM_STR);
$stmt->bindParam(':holder', $owner, PDO::PARAM_STR);
$stmt->bindParam(':iprice', $iprice, PDO::PARAM_STR);
$stmt->bindParam(':sprice', $sprice, PDO::PARAM_STR);
$stmt->bindParam(':incprice', $incprice, PDO::PARAM_STR);
$stmt->bindParam(':etime', $timestamp, PDO::PARAM_INT);
$stmt->bindParam(':img', $img, PDO::PARAM_STR);
$stmt->bindParam(':condition', $condition, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
if($stmt->execute()){
$worked ="yes";
}
}catch(PDOException $e){
echo $e->getMessage();
}
i cant tell why this statement wont execute, the $worked variable has not been set when it is the script is run. all database column names and datatypes have been checked correct as they are. ive never had a problem with a statement not executing until now. whats wrong? how do i go about debugging this?
If you setup the database connection with error mode exception PDO will throw an exception if something is wrong with your statement. I also see that you are using the MySQL driver for PDO. If you do this you should always disable emulated prepared statements. So I would write you connection as following (note that I have also set the encoding):
$pdo = new PDO('mysql:host=localhost; dbname=divebay;charset=utf8', $user, $pass);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Also see this post for more information about this.
Once you have done this you will see that your statement is wrong. You have one missing ) at the end of the statement:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
^
Modify this line:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
To
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
The difference is the ) at the end.
And tell me if it works now.

Categories