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

This question already has an answer here:
PHP Convert mysql to mysqli [duplicate]
(1 answer)
Closed 7 years ago.
I've created a MySQLi connection
$conn = new mysqli($servername, $username, $password, $dbname);
How do convert this code below to MySQLi
$query = mysql_query("SELECT * FROM `grid` where user_id = $user_id and status=0 ORDER BY id ASC");
$count = mysql_num_rows($query);
if($count > 0) {
while($fetch = mysql_fetch_array($query)) {
$record[] = $fetch;
}
}

$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT * FROM `grid` where user_id = ? AND status=0 ORDER BY id ASC";
$stmt = $conn->prepare($query);
if (!$stmt)
{
// display error
}
// Bind params
$stmt->bind_param("i", $id);
if (!$stmt->execute())
{
// your execute error
}
$result = $stmt->get_result();
$data = [];
while ($dataTmp = $result->fetch_assoc())
{
$data[] = $dataTmp;
}

Related

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();
}

how to replace current_date() to any date type by user

how to replace current_date() to any date type by user
example:
www.example.com/2025-01-04
or any date
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = current_date() ";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
Try this:
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['date'])
and preg_match('/^\d{4}(-\d{2}){2}$/', $_GET['date']) // primitive validation
) {
$date = $_GET['date'];
} else {
$date = date('Y-m-d');
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
$stmt->bind_result($domain);
$data = array();
while ($stmt->fetch()) {
$data[] = array('domain' => $domain);
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
I would recommend using a prepared statement here (assuming you are using mysqli).
A) Because you can dynamically assign either current_date() or variable using user input value to a placeholder.
B) The prepared statement would make this operation more secure since you are escaping all user input.
if (!empty($_POST['date'])) {
$user_date = $_POST['date'];
} else {
$user_date = "current_date()";
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $user_date);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
Depending on how you are getting the date from user, you may need to validate it to make sure that it is in the proper date/time format for mysql.

why its not working to me [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
i want to get the backgroundColor of the Name headerBackgroud and its not printing anything, can you please help me?
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB#1";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT backgroundColor FROM background WHERE Name = 'headerBackground'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo $row['backgroundColor'];
}
You mix up mysqli and mysql api, so just use PDO uniformly as given:
$dbc = new PDO('mysql:host=localhost;dbname='.$database, $user, $password);
$sql = "SELECT backgroundColor FROM background WHERE Name = :n";
$stmt = $dbc->prepare($sql);
$stmt->bindParam(':n', "headerBackground");
$stmt->execute();
if($stmt->rowCount() > 0){
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$headerB = $data['headerBackground'];
}

mysql to pdo JSON for ios

I'm trying to convert this mysql code into PDO code, yet I can only return one of my rows in JSON whereas the mysql code allows me all the rows.
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
And here is the PDO code I've got to so far
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$records = $row;
}
echo json_encode($records);
It looks like I have to fill some more of this post out with random gobldygook as it seems I haven't already gotten to the point.
forgot to push each row into records, therefore
$records[] = $row;
or use fetchAll()
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC); // to get all records at once
echo json_encode($records);

php switching to mysqli: num_rows issue

I recently started updating some code to MySQL improved extension, and have been successful up until this point:
// old code - works
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo $row['data'];
}
// new code - doesn't work
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
As shown I am trying to use the object oriented style.
I get no mysqli error, and vardump says no data... but there definitely is data in the db table.
Try this:
<?php
// procedural style
$host = "host";
$user = "user";
$password = "password";
$database = "db";
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row['data'];
}
}
mysqli_close($link);
// OOP style
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
$mysqli->close() ;
// In the OOP style if you want more than one row. Or if you query contains more rows.
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
while($row = $result->fetch_array()) {
echo $row['data']."<br>";
}
$mysqli->close() ;
?>
As it was said, you're not checking for the errors.
Run all your queries this way
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if no errors displayed and var dumps are saying no data - then the answer is simple: your query returned no data. Check query and data in the table.
In PHP v 5.2 mysqli::num_rows is not set before fetching data rows from the query result:
$mysqli = new mysqli($host,$user, $password, $database);
if ($mysqli->connect_errno) {
trigger_error(sprintf(
'Cannot connect to database. Error %s (%s)',
$mysqli->connect_error,
$mysqli->connect_errno
));
}
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql);
// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$num_rows = $result->num_rows; // or just count($rows);
$result->close();
// do something with $rows and $num_rows
} else {
//$result will be a boolean
}
$mysqli->close() ;

Categories