How to convert mysql to mysqli? [duplicate] - php

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I tired to convert my mysql to mysqli but seems to be getting a lot of errors and warnings i got no problem connecting to the data base but the rest of the code seems wrong what am i doing wrong?
sql:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("searchengine");
$sql = mysql_query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysql_real_escape_string($_GET['term']) .'%',
$_GET['results']));
while($ser = mysql_fetch_array($sql)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}
// don't forget to close connection
mysql_close();
?>
mysqli
<?php
mysqli_connect("localhost","root","","searchengine") or die("Error " . mysqli_error($link));
$result = mysqli_query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results']));
while($ser = mysqli_fetch_array($result)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}
mysqli_close();
?>

you can try it by creating a mysqli object like described here: http://www.php.net/manual/en/class.mysqli.php
or simply like this:
$db = new mysqli($hostname, $username, $password, $database);
and then query it like this:
$result = $db->query('SQL HERE');
in your case the code for mysqli would look like this
$db = new mysqli("localhost","root","","searchengine");
$result = $db->query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results'])
);
while($ser = mysqli_fetch_array($result)) {
echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}

Try using OOP style instead of procedural, it is much cleaner and more readable:
$mysqli = new mysqli("localhost", "root", "", "searchengine");
$result = mysqli->query(sprintf(
"SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
'%'. mysqli_real_escape_string($_GET['term']) .'%',
$_GET['results']));
May I also suggest you read some articles about how to use mysqli and preparted statements, instead of just hacking away and not reading the documentation. Using prepared statements removes the need for sprintf. Here are some useful links:
PHP Website - http://www.php.net/manual/en/book.mysqli.php
An article I found on google in about 5 seconds and looks quite good -http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/

In mysql, we used mysql_real_escape_string because you couldn't prepare statement.
Now with mysqli, you have the ability to prepare statements which is the preferred way.
<?php
$mysqli = new mysqli("localhost", "root", "password", "searchengine");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$query = "SELECT * FROM searchengine WHERE pagecontent LIKE ? LIMIT 0,?";
$stmt = $mysqli->prepare($query);
if (!$stmt) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$term = '%'.$_GET['term'].'%';
$result = $_GET['results'];
$stmt->bind_param("si", $term, $result);
$stmt->execute();
while ($ser = $stmt->fetch_assoc()) {
echo "<h2><a href='".$ser['pageurl']."'>".$ser['pageurl']."</a></h2>";
}
$mysqli->close();
?>

Related

How to fetch data from MySQL using mysql_fetch_array [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I am trying to fetch MySQL data using below code, but it seems have some mistake. Can anyone help please. Thank you!
<?php
$link = mysqli_connect("localhost", "myusername", "mypassword", "mydb") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM users WHERE id=2";
$res = mysqli_query($link, $query);
$userRow = mysql_fetch_array($res);
echo $userRow["user_firstname"];
?>
Thank you #Mario
<?php
$link = mysqli_connect("localhost", "myusername", "mypassword", "mydb") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM users WHERE id=2";
$res = mysqli_query($link, $query);
$userRow = mysqli_fetch_array($res);
echo $userRow["user_firstname"];
?>

How to Query in PHP/ MySQL when there is a period (.) in String

How do I query from a MySQL database when I have a period (.) in string using PHP.
$variable = "my.email#email.com";
$variable = mysqli_real_escape_string($conn, $variable);
$query = "Select * from table WHERE email = '$variable' ";
Apparently this works when I ran it in PhpMyAdmin SQl tab. But when I run it In my code it does not work. Other strings that don't have a period using the same code are working perfectly. What could be the issue
for those who are asking for my original code here it is
//I get the emails from the url
$notit = mysqli_real_escape_string($conn, $_GET['username']);
//I pass my variable in the query
$sql = "SELECT * ";
$sql.=" FROM ordrs ";
$sql.=" WHERE client_email = '$notit' ";
$query=mysqli_query($conn, $sql) or die("try again");
Try this code it works for me try using PDO.
try{
$pdo = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_username, $db_password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$email = "code.sample#mail.co.ke";
$stmt = $pdo->prepare('SELECT email FROM user WHERE email = ?');
$stmt->bindParam(1, $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Sample output by eg: echo '<h2>'. $user['email'] . '</h2>';
You should use prepared statements. Otherwise, possible of sql injection vulnerability.
Example:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("Select * from table WHERE email = ?");
$stmt->bind_param("s", $email);
// set parameters and execute
$email = "john.doe#example.com";
$stmt->execute();
I figured where the issue was the query was fine the error was coming from json_encode which I din't expect . I hope this question helps others in the future who are facing the problem questioned. Thanks for the help
thanks for the help. Cheers

How would I turn this into a prepared statement? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I'm new to prepared statements so I apologise in advance if this is a basic question but how would I turn the following code into a prepared statement and execute it later on?
<?php
$myQuery = "SELECT * FROM test WHERE ID=" . $_GET['ID'];
//run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($con));
?>
Take a look to http://www.w3schools.com/php/php_mysql_prepared_statements.asp, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php (mysqli lib), or http://php.net/manual/en/pdo.prepared-statements.php (PDO lib).
Ex:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare statement
$stmt = $conn->prepare("SELECT * FROM test WHERE ID=?");
// set parameters
$stmt->bind_param("i", $_GET['ID']);
// execute
$stmt->execute();
// close resources
$stmt->close();
$conn->close();
To do the call you could use somethign like;
$sCompanyCode = 'fkjahj12321';
$con = new PDO("connection string");
$sql = "SELECT CompanyID From Companies WHERE CompanyCode = :CompanyCode";
$st = $con->query( $sql );
$st->bindValue(":CompanyCode", $sCompanyCode, PDO::PARAM_STR);
$st->execute();
To retrieve 1st or singular result;
if($row = $st->fetch()){
return (int)$row[0];
}
For multiple results;
$aResults = array();
while ($row = $st->fetch()){
$aResults[] = $row;
}

PHP syntax wrong? Outputting Resource id #3

<?php
$link = mysql_connect('localhost', 'user', 'password');
if (!$link) {
die('Failed to connect to MySQL: ' . mysql_error());
}
$db_selected = mysql_select_db('mysql', $link);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
$query = sprintf("SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND
CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' .mysql_error() . "\n";
$message .= 'Whole query: ' .$query;
die($message);
}
while ($row = mysql_fetch_array($result)) {
echo $row['shop_id'];
}
mysql_free_result($result);
echo "end";
?>
I know SQL query works by copying/pasting into phpmyadmin. I want the script to just output a shop_id or series of shop_ids. Right now it outputs Resource id #3. I looked up how to fix it and mysql_fetch_array was supposed to be the answer. What am I doing wrong?
I'm looking over your query and I only see you selecting church_id and you want to output shop_id, you should include that in your select like so:
$query = sprintf("SELECT church_id, shop_id FROM hours WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);
You have several problems here, the first of which is that you are using the mysql extension which is unmaintained and officially deprecated (due to be removed). I suggest you try mysqli...
$link = new mysqli('localhost', 'user', 'password', 'mysql');
if ($link->errno) {
throw new Exception($link->error, $link->errno);
}
Whilst you've done a commendable job of securing your query, you really should be using the better tools available in mysqli, notably prepared statements...
$stmt = $link->prepare('SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), ?) AND
CURTIME() BETWEEN open_time AND close_time');
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
$stmt->bindParam('s', $day_of_week); // assuming $day_of_week is properly defined
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
Fetching data from a mysqli prepared statement is a little different to the old mysql_fetch_array however it's not difficult. One way is to use result binding
$stmt->bind_result($church_id);
while ($stmt->fetch()) {
echo $church_id;
}

Moving from MySQL to MySQLi

Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

Categories