Prepared Statements Mysql not working - php

I am trying to use prepared statements to select data from a table as the following. This method does not work.
$sql = "SELECT * FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$returnValue = $statement->execute();
return $returnValue;
$sql should be in the following format.
$sql = "SELECT * FROM `usrs` WHERE `username` = 'username' ";
however the above code does not place single quotes ' ' around username
I need to place username between two single quotes ' ' as shown. if I use just
$sql = "SELECT * FROM `usrs` WHERE `username` = username "
it does not work.
any suggesstions how to do that.

Read this carefully:
bool mysqli_stmt::execute ( void )
it means it returns boolean - that is not a usable object or an array.
You've to fetch the statement.
Here's the fix:
$sql = "SELECT * FROM `usrs` WHERE `username` = ? LIMIT 1";
$statement = $this->conn->prepare($sql);
$statement->bind_param("s",$username);
if ($statement->execute()) {
$result = $statement->get_result();
return $result->fetch_assoc();
}
return null;
P.S. Thank You #Phil for fixing my mistakes in my answer

Related

double data on mysql

I use the php operator && to select multiple data so that there is no duplication on mysql.
Does the code that I use below run fine? Is there a more simple use of PHP operators?
$date= date('Y/m/d');
$cekcount = mysql_num_rows(mysql_query("SELECT * FROM `pending_media` where `mediaid`='$dielz'"));
$cekcount2 = mysql_num_rows(mysql_query("SELECT * FROM `media` where `mediaid`='$dielz'"));
$selectcount = mysql_query("SELECT * FROM `media` where `date`='$date' AND `uplink`='$nam'");
$cekcount3 = mysql_num_rows($selectcount);
if($cekcount == 0 && $cekcount2 == 0 && $cekcount3 == 0){
mysql_query("INSERT INTO pending_media VALUES('','$nam','$dielz')");
Upgrade to mysqli, I'll recommend object-oriented syntax because it is nicer to work with.
In accordance with the best practice of "minimize calls to the database", I'll condense your three queries into a single, united SELECT call then check for a non-0 result.
My untested suggestion using mysqli's object-oriented syntax (I did test the SELECT query in PHPMyAdmin):
$query = "SELECT SUM(tally)
FROM (
SELECT COUNT(*) AS tally
FROM pending_media
WHERE mediaid = ?
UNION ALL
SELECT COUNT(*)
FROM media
WHERE mediaid = ? OR (date = ? AND uplink = ?)
) t";
$conn = new mysqli("localhost", "root","","dbname");
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $dielz, $dielz, $date, $nam);
$stmt->execute();
$stmt->bind_result($tally);
$stmt->fetch();
if (!$tally) {
$stmt->close();
// insert qualifying data
$stmt = $conn->prepare("INSERT INTO pending_media VALUES ('',?,?)");
$stmt->bind_param("ss", $nam, $dielz);
if ($stmt->execute()) {
echo "Insert Query Error"; // $stmt->error;
}else{
echo "Success";
}
}

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

How should I write PHP $_POST variable in a mysql_query function?

Simple question. How do i make the query work? I know you can't directly use $_POST in a query. But i do not know how to get this to work.
$sql = 'SELECT * FROM users WHERE `password` = $_POST[password] AND `username` = $_POST[username]';
$result = mysqli_query($link, $sql);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysqli_error($link);
exit;
I have also tried using the mysqli_real_escape_string like this :
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
This did not work as planned. As it did still not work.
Thanks,
Mike
use '' with string comparison of MySQL
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM users
WHERE `password` = '$username_sql' AND `username` = '$password_sql'";
Use prepared statements to avoid sql injection and syntax errors with commas .
$sql = 'SELECT * FROM users WHERE `password` = ? AND `username` = ?';
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "ss", $_POST['password'], $_POST['username']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result){
echo $row['username'] .'<br>';
}
I think it is necessary to add at least one example of prepared statements, just to show that it is not more difficult and it makes your application safer (SQL-injection).
$stmt = $mysqli->prepare('SELECT * FROM users WHERE `password` = ? AND `username` = ?');
$stmt->bind_param("ss", $_POST[password], $_POST[username]);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
// read the result...
$stmt->close();
Be aware that passwords should not be stored plain text, instead one should use the functions password_hash() and password_verify().
You answered your question yourself.
mysqli_real_escape_string() is the way to go.
$sql = 'SELECT * FROM users WHERE `password` = "' . mysqli_real_escape_string($_POST[password]) . '" AND `username` = "' . mysqli_real_escape_string($_POST[username]') . '"';

Doctrine DBAL Params in WHERE clause

I'm trying to filter my Doctrine DABL MySQL query using parameters in where clause:
$this->dbConn refers to doctrine db connection.
$this->tableName holds the correct table name.
$sql = "SELECT * FROM {$this->tableName} WHERE `category` = 'armor' AND ? != ?";
$stmt = $this->dbConn->prepare($sql);
$filterKey and $filterVal contain correct values.
$params = [
$this->dbConn->quoteIdentifier($filterKey),
$this->dbConn->quote($filterVal)
];
$stmt = $this->dbConn->executeQuery($sql, $params, [\PDO::PARAM_STR, \PDO::PARAM_STR]);
$result = $stmt->fetchAll();
$result contains rows where $filterKey == $filterVal opposed to expected
Following also does not works
$sql = "SELECT * FROM {$this->tableName} WHERE `category` = 'armor' AND :filterKey != :filterVal";
$stmt = $this->dbConn->prepare($sql);
$stmt->bindValue('filterKey', $this->dbConn->quoteIdentifier($filterKey), \PDO::PARAM_STR);
$stmt->bindValue('filterVal', $this->dbConn->quote($filterVal), \PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
$result contains rows where $filterKey == $filterVal opposed to expected
Am I missing something basic here?
BTW, I'm trying not to use queryBuilder.
Thank you.

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* 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
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

Categories