Prepared satements with bind_param() in PHP [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
Is there any way to write this code using prepared statements?
$sql = "SELECT *
FROM exercises
WHERE exercise_id IN (
SELECT DISTINCT e.exercise_id
FROM users u,users_subjects us, exercises e
WHERE u.username='".$_SESSION['username']."' AND us.user_id_fk=u.id AND e.subjects=us.subject_id_fk
);";
$result = $conn->query($sql);
I'm trying this way, but with the sencente ‘IN’, I’m not sure how to do it:
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='".$_SESSION['username']."' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
$stmt->bind_param("" );
$stmt->execute();
$stmt->close();

$username = $_SESSION['username'];
// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username=? and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
// then pass $username to bind_param()
$stmt->bind_param("s", $username);
Then the rest of your code should work. I'd also recommend testing your stmt commands for error handling. They all return booleans.
// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='?' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
if(!$stmt) echo "prepare failed: " . mysqli_error($conn);
Same can be done for bind_param() and execute().

Related

PDO fetch not working with INSERT, UPDATE then SELECT query [duplicate]

This question already has answers here:
PDO multiple queries
(1 answer)
PDO Transaction statement with insert and fetch output error
(1 answer)
Closed 1 year ago.
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');
SET #bookid = LAST_INSERT_ID();
INSERT INTO paper (papername) values('hhhhhhh');
SET #paperid = LAST_INSERT_ID();
UPDATE author SET bookid = #bookid, paperid = #paperid WHERE id = 11;
SELECT #bookid as bookid, #paperid as paperid FROM DUAL;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$numofnewParn =$stmt->rowCount();
if($numofnewParn>0){
$newParentDt = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($newParentDt);
}
I have set of inserts with LAST_INSERT_ID assigned to respective parameters.
Later, updating a table with the parameters.
until $stmt->execute(); is not problem.
My question is can I continue the query by adding SELECT and fetch the data like $stmt->fetch(PDO::FETCH_ASSOC)?
or does it not make sense? if so, is there any source?
because above code does not print out.
You need to use PDOStatement::nextRowset see here to move onto the next queries result in your multi statement... however a cleaner setup would be to break this down into single statement queries and use PHP variables to save your bookid and paperid values:
<?php
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$bookid = $pdoConnect->lastInsertId();
$sql = "INSERT INTO paper (papername) values('hhhhhhh');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$paperID = $pdoConnect->lastInsertId();
$sql = "UPDATE author SET bookid = $bookid, paperid = $paperid WHERE id = 11;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();

Prepare select statement in php [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
MySQLi Bind Param with an array for IN [duplicate]
(2 answers)
Closed 5 years ago.
I can not figure out how I can prepare my select statement.
$query = "SELECT name, art FROM table_one WHERE name LIKE ? AND art IN ?";
if ($stmt = $db_link->prepare($query)) {
$stmt->bind_param("ss", $name, $art);
$stmt->execute();
if ($stmt->errno){
//Deal with error
}
$name = "%Marc%";
$art = "('green', 'blue', 'red')";
$stmt->execute();
$stmt->bind_result($name, $art);
while ($stmt->fetch()){
//Output data
}
}
So the problem is, that something does not work with the syntax in the prepared statement. This is my first attempt at preparing statements.
I had the query working before without using a prepared statement, but I am forced to use that now.
The old query looked like this:
$query = "SELECT name, art FROM table_one WHERE name LIKE '%$name%' AND art IN ('$art')";
Thank you for your help.

Safe MYSQL querying using user input [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I just want to check how safe (if at all) my PHP-MYSQL queries are, I'm using user data which is coming through $_POST and then validating - the validation process of all data includes using mysqli_real_escape_string() on the string and trim(). The nature of some of my inputs however means that I don't restrict any characters on user input. Is what I'm doing safe and if not how could it be improved.
An example of an insert query (where $name and $description are $_POST data values which have been through a validation function.)
$sql = "INSERT INTO company(company_name, company_description) VALUES('".$name."', '".$description."')";
$result = mysqli_query($con, $sql);
An example of a select query (where $companyid is user input, real_escaped and stripped)
$sql = "SELECT * FROM events WHERE event_company=".$companyid."";
$result = mysqli_query($con, $sql);
Thanks in advance.
Here are your queries updated to use mysqli prepared statements.
$sql = "INSERT INTO `company` (`company_name`, `company_description`) VALUES(?, ?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('ss',$name,$description); // ss is for string string
$stmt->execute();
$result = $stmt->get_result();
and
$sql = "SELECT * FROM `events` WHERE `event_company` = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$companyid); // i indicates integer
$stmt->execute();
$result = $stmt->get_result();
There a type of hack called "SQL INJECTION" which can deceive your control. Read there for more information https://www.veracode.com/security/sql-injection

PDO Select form MYSQL db [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
There are many hints for this topic, I tried this: How to create a secure mysql prepared statement in php?
and many others, but nothing is working. If I want to select something from the database and query without parameters, it's ok. But if I want data for a column and table with parameters, it doesn't work, it returns empty array. Any hints?
There is my code:
function getDataByColumn($column, $table) {
try {
$connection = new PDO("mysql:dbname=vydap;charset=utf8;host=127.0.0.1", "...","...");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = "SELECT ? FROM ?";
// $query = "SELECT :column FROM :table";
$stmt = $connection->prepare($query);
// $stmt->bindParam(':column', $column);
// $stmt->bindParam(':table', $table);
$stmt->bindParam(1, $column);
$stmt->bindParam(2, $table);
$stmt->execute();
$result = $stmt->fetchAll();
var_dump($result);
}
This is flat-out wrong:
$query = "SELECT ? FROM ?";
placeholders can represent only VALUES. You cannot use placeholders for field/table/db names - those aren't values - they're idenfifiers.
SELECT foo FROM bar WHERE foo = 'baz'
a b c d e f g h
a- sql keyword
b- field identifier
c- sql keyword
d- table identifier
e- sql keyword
f- field identifier
g- operator
h- value
Of that entire query, only the h portion is a candidate for using a placeholder.
You can't use PDO placeholders on table or columns names. Those are only used for values:
$query = "SELECT * FROM yourTable WHERE someCol = ?";
$stmt->bindParam(1, $value);

How to return the result of a mysqli_query so I can use it in another function? [duplicate]

This question already has answers here:
MySQLi equivalent of mysql_result()?
(12 answers)
Closed 9 years ago.
I am trying to return the user's id number from the database but I can't figure out how to return the result of the query. I used to use mysql_result() so what would I need to do now that I'm using mysqli?
function user_id_from_username($username){
$query = mysqli_query($conn, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return (what?);
}
You haven't reaped one of the main benefits of moving from mysql to mysqli, which is using prepared statements to parameterize your queries and protect yourself from injection.
$query = mysqli_prepare($conn, "SELECT user_id FROM `users` WHERE username = ?");
mysqli_stmt_bind_param($query, "s", $username);
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $userid);
mysqli_stmt_fetch($query);
//$userid is now user_id
check this http://php.net/manual/en/mysqli.query.php for myqli_query usage. and this http://www.php.net/manual/en/class.mysqli-result.php on how to get the values from the result.

Categories