PHP not showing MySQL results with variable in query [duplicate] - php

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.

your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure

You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

Related

PHP bind_param not binding parameter [duplicate]

This question already has answers here:
MySQLI Prepared Statement: num_rows & fetch_assoc
(5 answers)
Closed 5 years ago.
I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:
$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
$stmt->bind_param("s",$search);
$stmt->execute();
while ($row = mysqli_fetch_array($stmt)) {
$item = [];
$item['id'] = $row['id'];
$item['first'] = $row['search'];
$item['last'] = $row['data'];
array_push($items, $item);
}
}
return $items;
Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'
But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.
I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.
I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.
Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.
Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.
You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:
$stmt = $conn->prepare(...);
$stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_array($result)) {
Or, in the fully OO manner:
while ($row = $result->fetch_array()) {

mysql_num_rows() error boolean given [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
i've got this part of code in my php app
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = ".$_POST['email'];
$num_rows = mysql_num_rows(mysql_query($find_user));
that return this error message:
mysql_num_rows() expects parameter 1 to be resource, boolean given
But i'm passing a query result to mysql_num_rows(). I've checked the query and it's correct (because if i execute it on phpMyAdmin it return the record).
Thanks in advance for all the help
You need to put your profile_contact_email values in quotes because to insert VARCARE field we need quotes around it. And use mysql_real_escape_string in your query to prevent sql injection
$email = mysql_real_escape_string($_POST['email']);
$find_user = "SELECT * FROM tcms_module_profiles WHERE
profile_contact_email = '".$email."'";
$result = mysql_query($find_user);
$num_rows = mysql_num_rows($result);
Note:- mysql is deprecated instead use mysqli or PDO
Your SQL query failed, resulting in mysql_query returning a boolean FALSE value. It failed because you didn't use quotes around your email.
Your script is also open to SQL injection, btw.
Use the following code:
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}';";
$result = mysql_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysql_num_rows($result);
Your code was missing '' around $_POST['email'] and you should check first for the query to be true. mysql_ is deprecated use mysqli_ or PDO extension. Mysqli & PDO
A mysqli version of above code
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}'";
$result = mysqli_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysqli_num_rows($result);
Note - you also need to change your mysql connection variables according to mysqli.
Try this...
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = '".$_POST['email']."'";

Sql injection get id solution [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I don't know how to make this code safe. I tried to use mysql_real_escape_string in the query variable like
$query = "select * from products where id= " . mysql_real_escape_string($products);
but didn't work, also tried to escape in the products variable, but got the same result.
Any sugestions?
Thanks.
<?php
/ Define vars.
$conn = mysql_connect('localhost', 'test', 'test');
$products = isset($_GET["products"]) ? $_GET["products"] : "";
$query = "select * from products where id=$products";
// List elements.
if ($conn)
{
mysql_select_db('testsqli');
$result = mysql_query($query);
// Table head.
echo '<table cellspacing="5" cellpadding="5">';
echo '<tr>';
echo '<td>Description</td>';
echo '<td>Price</td>';
echo '</tr>';
// Empty table?
if (#mysql_num_rows($result)==0)
{
echo '<tr>';
echo '<td><i>That\'s all!</i></td>';
echo '</tr>';
}
// Listing data in table.
while ($row = #mysql_fetch_array($result))
{
echo '<td>'.$row['Description'].'</td>';;
echo '<td>'.$row['Price'].'</td>';;
}
echo '</table>';
}
?>
You still need to add quotes, (and use msqli instead) like:
$query = "select * from products where id='" . mysqli_real_escape_string($products)."'";
// or
$query = sprintf(
"select * from products where id='%s'",
mysqli_real_escape_string($products)
);
I'd use prepared statements instead of MySQL escaping. Escaping skips over some of the wildcards, such as '%' and '*' which could also provide unanticipated results.
$stmt = $dbh->prepare("SELECT * FROM PRODUCTS WHERE ID=?");
$stmt->bindParam(1, $products, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
Also, keep in mind the following measures keep it safe:
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type. (In this case, verify that $products is formatted as expected, i.e. if your product catalog has indices of only nine characters, make sure it's not 100 characters long.) PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().
Reference: http://php.net/manual/en/security.database.sql-injection.php

Am I doing the mysqli right? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Every question which I asked on stackoverflow I received a question that It was easy to do a php injection into my script.
I've now a example and checked some tutorials on youtube.
Am I doing this right now?
This is an example how I'm working now
if($user->isLoggedIn()) {
$pakuser = $user->data()->username;
$sql = $db->query("SELECT * FROM users
INNER JOIN post ON users.username = post.add
WHERE post.id = $id AND post.add = '$pakuser'")
or die(mysql_error());
if ($sql === FALSE) {
}
if($row = $sql->fetch_object())
if($row->add)
{
?>
<p>edit this post<br><br>BEWARE OF DELETING YOUR CONTENT THERE IS NO GO-BACK<BR>Delete this post </p>
<?php
}
}
Everytime the user can manipulate your sql-query without any restriction, there is a security-issue. Here is an example:
$query_string = "SELECT * FROM user WHERE (name='$username' AND password='$password')";
if the user sends a password like:
"something') OR ('1' = '1"
the query will change to:
$query_string = "SELECT * FROM user WHERE (name='Name' AND password='something') OR ('1' = '1')";
Because '1'='1' is always true, this will return each user in your database.
Instead you can change the example above to:
$query = mysqli->prepare('SELECT * FROM user WHERE (name=? AND password=?)');
$query->bind_param('ss', $username, $password);
$query->execute();
This will filter all strings that could break your sql-query.
It seems like you are still just passing variables straight through into the query. Yes, this may work, but is not necessary secure.
You could have a look at using PDO instead, which has means of being able to verify the data type that you are wanting to pass through into your query rather than just passing a variable into the query string.
In terms of using mysqli, have a look at mysqli_real_escape_string if you have not already. It is well documented.

PDO Prepared Statement over ODBC Sybase "PARAM datastream" error

I am trying to convert some old PHP ODBC queries over to PDO Prepared statements and am getting an error I cannot find too much information on.
The Error is:
"[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]There is no host variable corresponding to the one specified by the PARAM datastream. This means that this variable '' was not used in the preceding DECLARE CURSOR or SQL command. (SQLExecute[3801] at ext\pdo_odbc\odbc_stmt.c:254)"
I am searching for a single row in the database using a 6 digit ID that is stored in the database as a VARCHAR but is usually a 6 digit number.
The database connection is reporting successful.
The ID passed by the query string is validated.
The prepared statement results in the above error.
The backup straight ODBC_EXEC statement in the else clause returns the data I am looking for.
//PDO Driver Connect to Sybase
try {
$pdo = new PDO("odbc:Driver={Sybase ASE ODBC Driver};NA=server,5000;Uid=username;Pwd=password;");
$pdo_status = "Sybase Connected";
} catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
if((isset($_GET['id'])) AND ($_GET['id'] != "")) {
//Validate ID String
if(!preg_match("/^[A-Za-z0-9]{5,7}/",$_GET['id'])) {
$query1_id = FALSE;
echo "Invalid ID";
exit;
} else {
$query1_id = $_GET['id'];
}
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= ?");
$query1->execute(array($query1_id));
if($query1->errorCode() != 0) {
$person_data = $query1->fetch(PDO::FETCH_ASSOC);
echo "Person Data from PDO: ";
print_r($person_data);
} else {
$errors = $query1->errorInfo();
echo $errors[2];
//Try the old way to confirm data is there.
$odbc_query1 = "SELECT * FROM People WHERE PersonId='$query1_id' ";
$person_result = odbc_exec($conn,$odbc_query1) or die("Error getting Data, Query 1");
$person_data = odbc_fetch_array($person_result);
echo "Person Data from ODBC_EXEC: ";
print_r($person_data);
}
It also fails if I use:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= :id ");
$query1->execute(array(":id"=>$query1_id));
Does anyone have experience with this error?
Edit: Sybase Manual says this about the error...
Error 3801: There is no host variable corresponding to the one specified by the PARAM datastream. This means that this variable `%.*s' was not used in the preceding DECLARE CURSOR or SQL command.
Explanation:
Adaptive Server could not perform the requested action. Check your command for missing or incorrect database objects, variable names, and/or input data.
Which is odd because my error (quoted at the top) doesn't tell me which variable has no host.
Also fails if I use...
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= :id ");
$query1->bindParam(':id',$query1_id,PDO::PARAM_STR); //Or PARAM_INT
$query1->execute();
The query works if I place the variable in the query like this...
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= '$query1_id'");
So I think it has something to do with the parameter not being bound to the placeholder but I can't figure out why.
If I can't work this out I'll have to revert to building my query as a string and hoping my input validation is bullet proof.
Your problem seems to be with the default data type PHP assigns to variables in the placeholders. The SQL Statement is looking for a number but PHP is interpreting it as something else. You can prevent this using quotes around the placeholder variable. Notice that in the statements that work you have apostrophes ('') around the value that PHP sees:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= '$query1_id'");
Try this when using the placeholder it should be the same:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= ':id'");

Categories