PHP PDO add edit update select statments - php

These are my PDO add, edit, delete ,select functions for my MVC pattern implementation.
I need to know if this implementation is correct using PDO.
These are Model Class functions:
public function getStudentById($id){
$stmt = $this->db->con->query("SELECT * FROM student WHERE id = '$id'");
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function addStudent($arrData){
$sql = " INSERT INTO student (name,age,address)".
" VALUES ('$arrData[name]','$arrData[age]','$arrData[address]')";
$stmt = $this->db->con->prepare($sql);
$stmt->execute();
return $this->db->con->lastInsertId();
}
public function editStudent($arrData){
$sql = " UPDATE student SET ".
" name='$arrData[name]',age='$arrData[age]',address='$arrData[address]'".
" WHERE id=$arrData[id] ";
$stmt = $this->db->con->prepare($sql);
$stmt->execute();
return $this->db->con->lastInsertId();
}
public function deleteStudent($id){
$stmt = $this->db->con->query("DELETE FROM student WHERE id = '$id'");
}

Correct or not, you can do it easier and safer. One of the main advantages of PDO is the support of parametrized queries, where you only write placeholders and let PDO insert the values. This will help protecting against SQL-injection, because PDO will do the correct formatting for you.
$sql = 'SELECT * FROM student WHERE id = ?';
$statement = $db->prepare($sql);
$statement->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$statement->execute();

Related

What's the proper way to return a single database result?

All I want to do is get the firstname result from this function, but it feels it's too much code to do that based on session id.
//query_functions.php
function find_name_by_id($id) {
global $db;
$sql = "SELECT firstname FROM admins ";
$sql .= "WHERE id='" . db_escape($db, $id) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$name = mysqli_fetch_assoc($result); // find first
mysqli_free_result($result);
return $name; // returns an assoc. array
}
// admin.php
id = $_SESSION['admin_id'];
$name = find_name_by_id($id);
// what is the shortest way to get this $name result?
To do this properly using prepared statements you actually need more code than that:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->free_result();
return $row[0];
}
I'm not sure what confirm_result_set is so I left it out.
Let's pretend that $db was a PDO object:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->execute([$id]);
return $stmt->fetchColumn();
}
Much less code involved. And for a higher-level API this will be abstracted to a single line of code.
In reality for all cases you'd want to do some error checking, account for no records being returned, etc. Also you should avoid global variables, they're very poor form. Put your code into a class or just use dependency injection as I've done.

Using a query result in another query

This is my first query, i want to use the multiple itemID's extracted for another query.
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT itemID from mycart where email = '".$email."' ";
$result = $conn->query($querystring);
$rs = $result->fetch_array(MYSQLI_ASSOC);
The second query that need
$query = "SELECT * from CatalogueItems where itemID = '".$itemID."'";
How do i make these 2 query run?
Firstly, Your code is open to SQL injection related attacks. Please learn to use Prepared Statements
Now, from a query point of view, you can rather utilize JOIN to make this into a single query:
SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = $email /* $email is the input filter for email */
PHP code utilizing Prepared Statements of MySQLi library would look as follows:
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = ?"; // ? is the placeholder for email input
// Prepare the statement
$stmt = $conn->prepare($querystring);
// Bind the input parameters
$stmt->bind_param('s', $email); // 's' represents string input type for email
// execute the query
$stmt->execute();
// fetch the results
$result = $stmt->get_result();
$rs = $result->fetch_array(MYSQLI_ASSOC);
// Eventually dont forget to close the statement
// Unless you have a similar query to be executed, for eg, inside a loop
$stmt->close();
Refer to the first query as a subquery in the second:
$query = "SELECT * from CatalogueItems WHERE itemID IN ";
$query .= "(" . $querystring . ")";
This is preferable to your current approach, because we only need to make one single trip to the database.
Note that you should ideally be using prepared statements here. So your first query might look like:
$stmt = $conn->prepare("SELECT itemID from mycart where email = ?");
$stmt->bind_param("s", $email);
This creates a variable out of your result
$query = "SELECT itemID FROM mycart WHERE email = :email";
$stm = $conn->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$itemID = $pers->itemID;
}

Using a variable value as a where statement inside PDO query

Lets say I have the following variable:
$where = "where `hats`='red'";
I want to inject this variable into a PDO statement. What is the proper way of doing this?
Is it like so?:
$sql = "select * from `clothing` :where";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':where', $where);
$stm->execute();
Any help would be greatly appreciated.
You can only bind values, not keywords, object names or syntactic elements. E.g., if you're always querying according to hats, you could bind the 'red' value:
$color = 'red';
$sql = "select * from `clothing` where hats = :color";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':color', $color);
$stm->execute();
If your where clause is really that dynamic, you'd have to resort to string manipulation (and face the risk of SQL injection, unfortunately):
$where = "where `hats`='red'";
$sql = "select * from `clothing` $where";
$stm = $this->app->db->prepare($sql);
$stm->execute();
// create a new PDO object by name $PDO in your connection file
In your function
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
I hope it will work. It will return the array, Traverse it as you like

pass FILTER_SANITIZE_STRING

I have a this query:
$query="select * from news where news_id = (select max(news_id) from news where news_id< $id)";
for execute I use class. in this class
public function query($query)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
Is there any way that < signal is not filtered?
Unfortunately, the whole idea is wrong. FILTER_SANITIZE_STRING won't help even slightest. Let alone it just breaks your SQL.
To protect SQL from injection you must use prepared statements. So instead of adding a variable directly to the query, add a question mark. And then put this variable into execute like this
public function query($query, $params)
{
$stmt = $this->mysqli->prepare();
$types = $types ?: str_repeat("s", count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt->get_result();
}
then just use it this way
$query="select * from news where news_id = (select max(news_id) from news where news_id<?)";
$data = $db->query($query, [$id])->fetch_all(MYSQLI_ASSOC)

How can I properly use a PDO object for a parameterized SELECT query

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 />";
}

Categories