PHP get Single Value query using - php

I have to use this code to get single record but in check var_dump get all record please advice me if any one know
$selected_result = $mysqli_lib_obj->query("SELECT * FROM orders WHERE id='".$order_id."'");

The right Solution would be to limit your result by SQL:
if ($stmt = $mysqli_lib_obj->prepare("SELECT * FROM orders WHERE id=? LIMIT 1")) {
$stmt->bind_param("i", $order_id);
$stmt->execute();
$selected_result = $stmt->get_result();
$num_of_rows = $selected_result->num_rows;
while ($row = $selected_result->fetch_assoc()) {
// Do something with $selected_result
}
$stmt->free_result();
$stmt->close();
}
And always use prepared statment, if you don't ... you are letting hacker open doors to your database .

you can use
"SELECT * FROM orders WHERE id='".$order_id."' Limit 1"

The Actual problem lies in the query itself- try this way.
$sql = "SELECT * FROM orders WHERE id='$order_id' limit 1";

Related

mysqli_query while loop to PDO

I am trying to upgrade my way to fetch data from sql from mysqli_query to fetchall.
$res = mysqli_query($db, "SELECT * FROM forum_index WHERE forum_over='yes'");
while ($arr = mysqli_fetch_assoc($res)) {
......
}
So when I use fetchAll() I'll get an array, Am I supposed to use foreach() then or is there a smarter way of doing this?
And to collect a single value from the DB this is the right way right?
$fid = (int)$_GET['id'];
$thread = $db->query("SELECT * FROM forum_threads WHERE f_id=".$fid)->fetch_array();
echo $thread['id'];
You don't need to use fetchAll() just because you're using PDO. If the query returns a large amount of data, this could slow things down because it has to collect it all into memory. You can use the same kind of loop as in your mysqli code:
$res = $pdo->query("SELECT * FROM forum_index WHERE forum_over='yes'");
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
...
}
As to your second question, you should use a parametrized query, not substitute variables.
$stmt = $pdo->prepare("SELECT * FROM forum_threads WHERE f_id= :id");
$stmt->bindParam(':id', $_GET['id']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
...
}

how to get found rows while executing a query with limit in mysqli?

I am using jquery datatable with a serverside pagination (php rest server)
and i have to get the full count when i execute a query with limit
After searching, I found that i can use FOUND_ROWS() but it won't work for me
here's the code
$sql = "select SQL_CALC_FOUND_ROWS * from `products`".($key?" WHERE id=$key":'')." ORDER BY ".$cols[$_GET['order'][0]['column']]." ".$_GET['order'][0]['dir']." LIMIT ".$_GET['start']." ,".$_GET['length'];
$sql2="SELECT FOUND_ROWS() as countall";
$result = mysqli_query($link,$sql);
$result2 = mysqli_query($link,$sql2);
$count= mysqli_fetch_object($result2);
var_dump( $count->countall);
$data = array();
for ($i=0;$i<mysqli_num_rows($result);$i++) {
$data[$i]= mysqli_fetch_object($result);
}
Is there any mistake i made ?
I want just return the countall value
The solution was to change mysqli_fetch_object into mysqli_fetch_assoc

PHP PDO - incremental for loop that fetches the next array row with each loop

I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);

Last ID not showing

I am trying to grab the largest ID number from the database. The output should be 15 but it shows 1. My PHP script:
$sql = "SELECT MAX(id) AS id FROM employees";
$sql = $db->prepare($sql);
$lid = $sql->execute();
I am outputting it here:
<input type="number" name="id" value="<?php echo $lid; ?>" disabled>
I have also tried:
$sql = "SELECT id FROM employees ORDER BY id DESC LIMIT 1";
I tried the command on phpMyAdmin. It worked fine. The output was 15. So, I suspect that there are no problems in the query.
What is the problem, then?
You should FETCH i.e., $sql->fetch(PDO::FETCH_ASSOC);
So, You shall have something like
$sql = "SELECT MAX(id) FROM employees";
$sql = $db->prepare($sql);
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
Note : Simply $lid = $sql->execute(); means it will assign whether the query is executing or not.
As your query is executing it is returning true which is 1
Update : If you are not binding any values you don't even need to prepare, you shall fetch it directly like Adelphia said
$sql = $db->query("SELECT MAX(id) FROM employees");
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
No need for prepared statements since it's a static query.

What would be the most efficient way to SELECT, then DELETE this immediately

What would be the most efficient way to SELECT this, then DELETE it immediately.
SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;
How could I take this same select query, but also make it delete what it selected in the most efficient way?
$query = 'SELECT * FROM `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;';
$result = mysql_query($query);
$record = mysql_fetch_assoc($result);
$query = 'DELETE FROM `usersOnline` WHERE id = ' . $record['id'];
mysql_query($query);
with mysql, you would have to do one and then the other. you would use the key from the select result to then delete that record directly afterwards. in this example, i am assuming your primary key column is named "id". you would replace the myssql functions with whichever method you are using to access the database of course.
you can do like this nested query
DELETE
FROM SomeTable
WHERE EXISTS
(SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1;
)
thanks
use DELETE FROM: http://dev.mysql.com/doc/refman/5.0/en/delete.html
I know this example mixed prepared statments with regular statements. But it's up to the developer how to write the code. This is just a proof of concept, kept simple for easy reading.
$mysqli = new mysqli('localhost', 'user', 'password', 'userTable');
$result = $mysqli->query("SELECT * from `usersOnline` WHERE timestamp>NOW()-INTERVAL 5 SECOND ORDER BY rand() LIMIT 1");
$stmt = $mysqli->prepare("DELETE FROM 'usersOnline WHERE id = ?");
while ($row = mysql_fetch_assoc($result)) {
$stmt->bind_param('i', $row["id"]);
$stmt->execute();
}
$stmt->close();
$mysqli->close();

Categories