PHP with PDO problem mysqli_stmt::fetch() [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 2 years ago.
I need to convert my code to PDO and I don't know where is the problem.
$user = $_SESSION['user_email'];
$get_user = "SELECT * FROM users where user_email='$user'";
//This 2 lines was there in original
$run_user = mysqli_query($con,$get_user); //original
$row=mysqli_fetch_array($run_user); //original
//Converting to PDO
$run_user = $con->prepare($get_user);
$run_user->execute();
$row = $run_user->fetch(PDO::FETCH_ASSOC); //line 27
// line 38 and 39
$user_id = $row['user_id'];
$user_name = $row['user_name'];
My errors are:
Warning: mysqli_stmt::fetch() expects exactly 0 parameters, 1 given in
/Applications/XAMPP/xamppfiles/htdocs/network/includes/header.php on
line 27
Notice: Trying to access array offset on value of type null in
/Applications/XAMPP/xamppfiles/htdocs/network/includes/header.php on
line 38
Notice: Trying to access array offset on value of type null in
/Applications/XAMPP/xamppfiles/htdocs/network/includes/header.php on
line 39

To convert your code to PDO you must ensure that you connect with PDO first. These are two very different APIs and you can't mix them.
First connect:
$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'pass', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Then prepare and execute a statement. Pay attention to never include variables directly in SQL. Every piece of data should be bound separately. In your SQL, put ? where the data should be bound to, and then pass an array with values in execute()
$run_user = $pdo->prepare('SELECT * FROM users where user_email=?');
$run_user->execute([
$_SESSION['user_email']
]);
Now you can fetch the data. Make sure that your SQL actually fetched something before trying to access it.
$row = $run_user->fetch(PDO::FETCH_ASSOC);
if($row) {
$user_id = $row['user_id'];
$user_name = $row['user_name'];
}

You're mixing the mysqli and PDO interfaces. This isn't possible.
See this demo on how to do the same thing in PDO.
<?php
// Create a database using PDO, by passing a DSN (Data Source Name), username, and password.
// Replace yourserverhost, yourusername, yourpassword with the real credentials.
// Depending on the charset of your tables, you may want to change utf8mb4 as well,
// although this is a typical value.
$pdo = new PDO(
'mysql:host=yourserverhost;dbname=yourdatabasename;charset=utf8mb4',
'yourusername',
'yourpassword'
);
$user = $_SESSION['user_email'];
$sql = 'SELECT * FROM users where user_email=?';
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $user, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
$user_name = $row['user_name'];
Your initial query is rewritten with a positional parameter (?).
The query is then made into a prepared statement to avoid SQL injection. The variable is bound using bindValue, starting at index 1. Other flavors of parameter binding are available.
PDOStatement::execute() runs the query.
PDOStatement::fetch(PDO::FETCH_ASSOC) fetches your row.
Do stuff with $row['user_id'] and $row['user_name'].

Related

Is it possible to pass a "PHP" variable that is passed by an URL as comparison element for a SQL query? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I've set a local server using PHPMyAdmin, and I'm presenting some dynamic data that is stored in that server using some PHP, HTML and SQL. The problem is that whenever I pass a variable that is stored using $variable = mysqli_real_escape_string($conn, $_GET["variable"]); and then I use that variable in a SQL query similar to this one $sql = 'SELECT * FROM assets WHERE variable="$variable";. The array that is generated is empty.
When I do a print_r($variable);, I get the variable that the code is expecting, so I'm not sure why the query sends an empty array. Then, when I hardcode the SQL query with the value of print_r($variable), the correct array is obtained from the query.
Code in PHP that is not working
$variable = mysqli_real_escape_string($conn, $_GET["variable"]);
print_r($_GET["location"]);
// make SQL
$sql = 'SELECT * FROM assets WHERE variable="$variable"';
Where $conn = mysql_connect('localhost', 'user', 'password', 'table');
The connection is correct though
then for example when I hardcode it using the result I get from
print_r($_GET["variable"]); prints N1 on the screen
This PHP is working, but it won't be dynamic
$sql = 'SELECT * FROM assets WHERE variable="N1';
I'm expecting to see all the results were the field variable = to a $_GET["variable"], where $_GET["variable"] is stored in $variable, but all I'm getting is an empty string.
You could use a prepared statement and binding param (for this you don't need the real string escape id done by the msqli prepared and binding)
$conn= new mysqli('localhost', 'user', 'password', 'your_db');
$myVar = $_GET["location"];
$sql = 'SELECT * FROM assets WHERE variable=?';
$query = $conn->prepare( $sql);
$query->bind_param('s',$myVar);
$result = $query->execute();
Try this code may be solve issues.
$conn= new mysqli("localhost","my_user", "my_password", "world");
$sql = 'SELECT * FROM assets WHERE variable='.$_POST["variable"];
mysqli_query($conn,$sql);

Prepared statement in PostgreSQL, string and number

php code:
$con = new PDO($this->dsn, $this->login, $this->password);
$stmt = $con->prepare($selectSql);
$stmt->execute(array(
'login' => $login
));
and sql query:
$selectSql = 'SELECT id
FROM public.users
WHERE (numberType = :login OR stringType = :login)';
The problem is that I do not find it desirable to edit PHP Code and add new variables to the example 'loginNumber' => (int) $login.
How can I fix it so that the SQL search result itself would be transferred to number value?
numberType = (:login)::Integer parameter did not work.
I have revised my answer given new comments, you will need to detect what data format has been provided. This is tricky as it seems your data always comes as a string, even if the string contains a raw integer.
The sloppy way to do this is to do a quick is_numeric check... but this will parse any numeric value as true... even floats? On-top of that, variable binding assumes string by default in PDO, to bind anything else you must verbosely define it.
Here is some loose code to give you an idea, but you may have to improve the $isNumericLogin logic for more accurate results for numeric non-integer login values.
$con = new PDO($this->dsn, $this->login, $this->password);
// Generate correct query given the data format
$isNumericLogin = is_numeric($login);
$selectSql = $isNumericLogin ?
'SELECT id FROM public.users WHERE number = :login' :
'SELECT id FROM public.users WHERE string = :login';
$stmt = $con->prepare($selectSql);
// Bind the correct data format based
$isNumericLogin ?
$stmt->bindValue('login', $login, PDO::PARAM_INT) :
$stmt->bindValue('login', $login);
$stmt->execute();

Fatal error: Cannot pass parameter 2 by reference when using PHP and MYSQL [duplicate]

This question already has answers here:
Cannot pass parameter 2 by reference - uuid PDO
(4 answers)
Closed 1 year ago.
I am using PHP PDO to insert into a MYSQL database using PHP. I am getting the error:
Fatal error: Cannot pass parameter 2 by reference in
/home/sandyit/public_html/hosting/findibuzz/design2/sign-up.php on
line 200
This is my code:
$ID is an auto incremented integer while the rest are varchar variables filled out as below as an example:
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbusername', 'dbpass');
$FULLNAME = "David";
$PW_HASH = "sadsad";
$SALT = "adadad";
$EMAIL_ADDRESS = "david#gmail.com";
$ID=0;
$addrequest = $db->prepare("INSERT INTO FB_USERS (ID,FULL_NAME,PASSWORD,PASSWORD_SALT,EMAIL_ADDRESS) VALUES (:ID,:FULL_NAME,:PASSWORD,:PASSWORD_SALT,:EMAIL_ADDRESS)");
$addrequest->bindParam(':ID',$ID, PDO::PARAM_INT);
$addrequest->bindParam(':FULL_NAME',$FULL_NAME, PDO::PARAM_STR);
$addrequest->bindParam(':PASSWORD',$PW_HASH, PDO::PARAM_STR);
$addrequest->bindParam(':PASSWORD_SALT',$SALT, PDO::PARAM_STR);
$addrequest->bindParam(':EMAIL_ADDRESS',$EMAIL_ADDRESS, PDO::PARAM_STR);
$addrequest->execute();
$addrequest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I know i have something wrong, but i cannot spot the error, can i have some advise please?
Thanks
Just for reference. I know this wont help solve your problem, but you could do something like this (see code below) to achieve the same result:
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbusername', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO FB_USERS (FULL_NAME,PASSWORD,PASSWORD_SALT,EMAIL_ADDRESS)
VALUES (:FULL_NAME,:PASSWORD,:PASSWORD_SALT,:EMAIL_ADDRESS)";
$stmt = $db->prepare($sql);
$params = array
(
'FULL_NAME'=>'David',
'PASSWORD'=>'sadsad',
'PASSWORD_SALT'=>'adadad',
'EMAIL_ADDRESS'=>'david#gmail.com'
);
$stmt->execute($params)
I find it easier to work with an array and than to just pass it to the statment.
But I guess its just a mather of taste.
Like I said this is just for reference and wont help you resolve your issue.
Remove quotation marks from '$ID'
$addrequest->bindParam(':ID',$ID, PDO::PARAM_INT);

mysqli::prepare(): Couldn't fetch MySQL [duplicate]

This question already has answers here:
mysqli::query(): Couldn't fetch mysqli
(4 answers)
Closed 9 months ago.
I started using mysqli_* functions instead of the old mysql_* functions in PHP, and I'm having a bit of a problem with this code:
public function addUser($table, $code = false, $rows = false) {
if (!$code) {
header("Location: " . $this->authenticate());
} else {
$this->getToken($code);
}
$user = $this->getEndpoint('users/current', false, true);
$user = $user->response->user;
if (!$rows)
$rows = array(
"remote_id" => $user->id,
"firstName" => $user->first_name,
"lastName" => $user->last_name,
"photo" => $user->photo->medium,
"gender" => $user->gender == 'male' ? 1 : 2,
"email" => $user->contact->email,
);
$rows['access_token'] = $this->accessToken;
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'"); //line 136
$stmt->execute(); //line 137
}
The code returns these 2 errors:
Warning: mysqli::prepare(): Couldn't fetch MySQL in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 136
Fatal error: Call to a member function execute() on a non-object in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 137
What is the reason for 'Couldn't fetch MySQL'? The database connection is correct, it works in other classes, and the query returns a valid result, if I echo it and execute it in phpMyAdmin. Also, my variable is named mysql NOT mysqli!
You should read more about the difference between MYSQL to MYSQLi.
While your code is:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'");
You should do it like this:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = ?");
$stmt->bind_param("s" , $this->accessToken ); //Used 's' as I guess that the accessToken is a string
The binding part is the critical part of the prepare thing. (Your queries are safe)
After that you can use $stmt->execute(); and get_result().
For the first error: you probably closed the connection somewhere before this code, and this is why ($stmt -> close() )
For the second error: when you use (prepare()), you first introduce a SQL template to the database, which then has to pass the parameters to the "bind_param()" method to send it to the database with another protocol (to prevent SQL injection) and reduce the request and attach the parameters to SQL with execute() method

My code should each the value of the $age variable, but instead it echoes the word "age"?

This is the code I'm using:
<?php
// Set the MySQL Configuration
$db_host = "";
$db_user = "";
$db_password = "";
$db_name = "";
$db_table = "";
// Start Connection
$db_connect = mysql_connect ($db_host, $db_user, $db_password);
// Select Database
$db_select = mysql_select_db ($db_name, $db_connect);
// Update Values in Database
$query = "UPDATE $db_table SET
age = age + 1,
land = '".$_POST['data3']."'
WHERE name = '".$_POST['data1']."'
";
// Execution MySQL query
$result = mysql_query($query) or die(mysql_error($db_connect));
//Close MySQL connection
mysql_close($db_connect);
//HTTP Response
echo " your age: age";
?>
I want to echo the value of the $age variable, but instead I always get the word "age." For example, the code should echo your age: 5 but instead it outputs your age: age
First, you'll need to run a SELECT query to retrieve the updated value of age. The query should look something like this:
"SELECT age FROM db_table_name WHERE name = ?"
Once you've obtained the result of that query, with say PDO::fetch (see my note below about PDO) and set it to the variable $age, you can output it with an echo statement:
echo "Your age: $age";
Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
The reason I'm not giving you the exact code for this is because it shouldn't be done with the mysql_* functions at all. Creating an SQL query with data directly from $_POST like this is extremely dangerous code to use and an incredibly bad idea all around. Never do this. You open yourself up to numerous SQL injection attacks. Even using mysql_real_escape_string is not enough. You should be using prepared statements.
UPDATE: Here is a simple example that's close to what you're asking, but using PDO and prepared statements. This is by no means a comprehensive example, since there are several ways to alter it that will still work (e.g. prepared statements allow you to execute multiple statements on the server in one statement), and I don't have a working server at the moment to test to make sure it's exactly what you need, but I hope it gets the point of across.
<?php
// Create the database connection
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
// Set PDO/MySQL to use real prepared statements instead of emulating them
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// The UPDATE query we're going to use
$update_query = "UPDATE `db_table_name` SET age = age + 1, land = :land WHERE name = :name";
// Prepare the query
$stmt = $db->prepare($update_query);
// Bind variables to the named parameters in the query with their values from $_POST
$land = $_POST['data3'];
$name = $_POST['data1']
$stmt->bindParam(':land', $land);
$stmt->bindParam(':name', $name);
// Execute the statement on the server
$stmt->execute();
// The SELECT query we're going to use
$select_query = "SELECT age FROM `db_table_name` WHERE name = :name";
// Again, prepare the query
$stmt_select = $db->prepare($select_query);
// Bind the paramters (in this case only one) to the new statement
// $name is already set from before, so there is no need to set it again
$stmt_select->bindParam(":name", $name);
$stmt_select->execute();
/*
* With no arguments, PDO::fetchColumn() returns the first column
* in the current row of the result set. Otherwise, fetchColumn()
* takes a 0-indexed number of the column you wish to retrieve
* from the row.
*/
$age = $stmt_select->fetchColumn();
echo("Your age: $age");
?>
All of this information came directly from the PHP documentation on prepared statements and PDO::fetchColumn().

Categories