Trouble converting PDO query to MySQLi - php

I have a query that is working fine in PDO but I am needing to convert the query to MySQLi to be compatible with an older server.
Here is the PDO query:
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username=:username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $username, PDO::PARAM_STR );
$st->execute();
while ( $row = $st->fetch() ) {
$db_username = $row['username'];
$db_password = $row['password'];
}
Here is what I have to MySQLi, but it doesn't seem to be working:
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT * FROM users WHERE username=$username";
if ($result = $mysqli->query($query)) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
Any help would be very much appreciated :)

Try using the mysqli prepared statement system
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$query = "SELECT username, password FROM users WHERE username=?";
$prep = $mysqli->prepare($query);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_result(); // Make sure you have mysqlnd installed
if($result) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
If you don't have mysqlnd installed then the less intuitive way involves bind_param
$prep->execute();
$prep->bind_result($db_username, $db_password);
$prep->fetch();

Related

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

PHP PDO MySQL get entries from Access and INSERT into MySQL

My goal here is to replicate a local MS Access database into my MySQL database (using php PDO)
The MS Access database is located on a network shared drive and updates itself with new entries every 6 hours.
In the code below I retrieved the max id number from MySQL table 'production_schedule', then I made an ODBC connection to retrieve all entries from MS ACCESS database that are greater than the max id number.
But now I cannot figure out how to insert these new entries into the MySQL table 'production_schedule'.
Can anyone please help?
<?php
/*USING XAMPP*/
$dsn = "mysql:host=localhost;dbname=qmsdb;charset=utf8";
$uname = "root";
$pword = "";
$db = null;
$limit = 10;
$counter = 0;
while (true) {
try {
$db = new PDO($dsn, $uname, $pword);
$db->exec( "SET CHARACTER SET utf8" );
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
$db->setAttribute( PDO::ATTR_PERSISTENT, true );
break;
}
catch (Exception $e) {
$db = null;
$counter++;
if ($counter == $limit)
throw $e;
}
}
$aid = $db->prepare("SELECT MAX(id) FROM production_schedule");
$aid->execute();
$big_id = $aid->fetchColumn();
$refid = intval($big_id);
$conn=odbc_connect('Prod_Schedule','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM Schedule WHERE ID > $refid";
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
***** INSERT CODE TO PUT THESE MS ACCESS ENTRIES INTO THE MYSQL TABLE ******
?>
something like this maybe:
while(odbc_fetch_row($rs)){
$sql = "INSERT INTO production_schedule (fieldName1, fieldName2, fieldName3) VALUES (?, ?, ?)";
$stmt = $dbh->prepare($sql);
for($i=1;$i<=odbc_num_fields($rs);$i++){
$stmt->bindValue($i, odbc_result($rs,$i));
}
$stmt->execute();
}
Note: depends on how many data you have to dump, you should use a solution like this: PDO Prepared Inserts multiple rows in single query to reduce risk of PHP timeout.
I just tested the following code and it seems to work okay for me:
$dsn = "mysql:host=localhost;port=3307;dbname=myDb;charset=utf8";
$uname = "root";
$pword = "whatever";
$mysqlDb = new PDO($dsn, $uname, $pword);
$mysqlDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$mysqlSql = "INSERT INTO clients (LastName, FirstName) VALUES (?, ?)";
$mysqlCmd = $mysqlDb->prepare($mysqlSql);
$LastName = '';
$FirstName = '';
$mysqlCmd->bindParam(1, $LastName, PDO::PARAM_STR, 255);
$mysqlCmd->bindParam(2, $FirstName, PDO::PARAM_STR, 255);
$connStr =
'Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Public\\Database1.accdb;';
$accessDb = odbc_connect($connStr, "", "");
$accessSql = "SELECT LastName, FirstName FROM Clients";
$accessResult = odbc_exec($accessDb, $accessSql);
while ($accessData = odbc_fetch_array($accessResult)) {
$LastName = $accessData["LastName"];
$FirstName = $accessData["FirstName"];
$mysqlCmd->execute();
}
First create a function to insert the values into MySQL, then loop through the ODBC results;
function createProductionSchedule($company,$person,$order){
$mysqli_con=mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno($mysqli_con))
{
echo 'Failed to connect to MySQL';
}
//Obviously your own fields here
$company = mysqli_real_escape_string($mysqli_con, $company);
$person = mysqli_real_escape_string($mysqli_con, $person);
$order = mysqli_real_escape_string($mysqli_con, $order);
$sql = "INSERT INTO production_schedule VALUES ('$company','$person','$order')";
mysqli_query($mysqli_con, $sql);
return mysqli_insert_id($mysqli_con);
mysqli_close($mysqli_con);
}
Then in your code section
while (odbc_fetch_row($rs))
{
$company=odbc_result($rs,"Company");
$person=odbc_result($rs,"Person");
$order=odbc_result($rs,"Order");
//Call the function to insert the record
createProductionSchedule($company,$person,$order);
}
odbc_close($conn);

mysqli does not execute Select statement

I have the code bellow. When I use this code without the WHERE clause, all the users from the table are displayed, as expected. But when the WHERE clause is used, nothing is displayed.
What could be the cause and how can I fix it?
Thank you!
function requestUser($user) {
$DBHost = "localhost";
$DBUser = "dbUser";
$DBPass = "dbPass";
$DBName = "dbName";
$db = new mysqli($DBHost, $DBUser, $DBPass, $DBName);
if ($db -> connect_errno > 0) {
$lbOK = false;
}
else {
$lbOK = $db -> set_charset('utf8');
}
if ($lbOK) {
$id = NULL;
$user_name = NULL;
$user = htmlentities($user, ENT_QUOTES);
$lcSQL = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db -> prepare($lcSQL);
$ok = $stmt -> bind_param('s', $user);
$ok = $stmt -> execute();
$ok = $stmt -> bind_result($user_name);
while ($row = $stmt -> fetch()){
echo $user_name;
}
$stmt->close();
}
}
There are many major faults with your code, some of them can be responsible for the problem, and some not. But nevertheless, they all have to be corrected
Never connect co database inside of an application function. Connect somewhere in the bootstrap file, once, and use that single connection throughout all the application.
Do not use htmlentities with whatever database interactions. It may easily spoil the data
Always check for the the errors
Do not use mysqli, it is unusable. Use PDO instead.
$dsn = "mysql:host=DBHost;dbname=DBName;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$DBUser, $DBPass, $opt);
function requestUser($user) {
global $db;
$sql = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($user));
return $stmt->fetchColumn();
}
echo requestUser($user);
if it still doesn't work, verify it this way
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
and then try to run in console/phpmyadmin to find out what's wrong with your data/value

How can I use one connection for 2 or more functions?

I use PHP's PDO to connect to MySQL. I have this code for connection:
$dbh = new PDO ( $db_host.$db_database, $db_user, $db_pass );
$dbh->exec ( "set names utf8" );
I have a function in another file:
function Image()
{
include 'config/connect.php';
#connected
$sql = 'Select * from settings where name="X" ';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
$Template = $row->web_site_template;
echo "Template";
}
I can use include connect.php file for that, but it's not true.
I want use one function like connection() for connect to the mysql on all other functions, like:
function Image()
{
connection();
$sql = 'Select * from settings where name="X" ';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
$Template = $row->web_site_template;
echo "Template";
}
This is the function. Put it in any file you like to.
function connection() {
$db_host = "..."; $db_database = "..."; $db_user = "..."; $db_pass = "...";
$GLOBALS["dbh"] = new PDO ( $db_host.$db_database, $db_user, $db_pass );
$GLOBALS["dbh"]->exec ( "set names utf8" );
}
This is your main code. Include the file with the code above if you decided to put it in another file.
connection();
$sql = 'Select * from settings where name="X" ';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
$Template = $row->web_site_template;
echo "Template";
I would consider it bad coding style though.
I find a best solution for my question (How you can use a MYSQL connection for 1 or more functions):
$db_database ="YourTableName";
$db_user ="YourUsername";
$db_pass ="YourPassword";
$db_host ="YourHostName";
$dbh = new PDO ( "mysql:host=$db_host;dbname=$db_database", $db_user, $db_pass );
$dbh->exec ( "set names utf8" );
$database = $dbh; // Here you can use $dbh too, but I use $database to understand the difference here .
#start function
function Template(){
global $database; //use $database as global
$sql = 'Select * from YourTableName where column="Record"';
$stmt = $database->prepare($sql); //use $database Instead $dbh
$stmt->execute();
$row = $stmt->fetchObject();
$Template = $row->web_site_template;
echo $Template;
}
Template(); // Here is your result.

Categories