I'm trying to get a limit query working. So far I've verified the following:
All input it valid and correct.
The Query works when manually run against MySQL
The Values are Cast to INT. I have even replcated the variables with the int value.
try {
$sql = "SELECT * FROM sensor_data WHERE sid=:sid ORDER BY id DESC LIMIT :starting_limit, :recordlimit";
$core = CoreDB::getInstance();
$sth = $core->dbh->prepare($sql);
$sth->execute(array(':sid' => $sensor->getID(), ':starting_limit' => (int)0, ':recordlimit' => (int)10));
// $sth->execute(array(':sid' => $sensor->getID()));
$results = $sth->fetchAll();
var_dump($sth->rowCount());
if ($sth->rowCount() > 0) {
foreach($results as $row){
$id = $row['id'];
var_dump($id);
}
}
}
catch(Exception $e){
}
Any advice is appreciated
The only solution I've found is to manually bind params rather than put them in an array in the execute method.
try {
$sql = "SELECT * FROM sensor_data WHERE sid=:sid ORDER BY id DESC LIMIT :starting_limit, :recordlimit";
$core = CoreDB::getInstance();
$sth = $core->dbh->prepare($sql);
$sth->bindValue(':sid', $sensor->getID(), PDO::PARAM_INT);
$sth->bindValue(':starting_limit', 0, PDO::PARAM_INT);
$sth->bindValue(':recordlimit', 10, PDO::PARAM_INT);
$sth->execute();
$results = $sth->fetchAll();
var_dump($sth->rowCount());
if ($sth->rowCount() > 0) {
foreach($results as $row){
$id = $row['id'];
var_dump($id);
}
}
}
catch(Exception $e){
}
If anyone is aware of how to get it working in the execute method please let me know and I will update the answer.
Related
I have to fetch result in single row but I can't run multiple rows. How can I fix this?
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
I Got Result Like Wise This
{"ID":2,"Name":"Anju"}
But i need to get all user result .my code is here
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
$stmt->close();
return $result;
}
I got the error
Fatal error: Call to a member function fetch_array() on a non-object in line 5
The line is:
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))
my expecting result is
{"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bindValue(1, $id);
Try that way
And try to fetchAll instead of fetch_array
You could make following correction.
Change
$rows->fetch_assoc(MYSQLI_ASSOC)
to
$rows->fetch_assoc()
It should look like
if ($stmt->execute()) {
$rows = $stmt->get_result();
$result = array();
while ($row = $rows->fetch_assoc()){
$result[] = $row;
}
$stmt->close();
return $result;
} else {
return NULL;
}
Suggestion : Always specify the list of columns in your SELECT, which makes query execution faster.
Please read php manual
my code PHP in mySQLquery to unique product id function
function kode($tabel, $inisial){
$struktur = mysql_query("SELECT * FROM $tabel");
$field = mysql_field_name($struktur,0);
$panjang = mysql_field_len($struktur,0);
$qry = mysql_query("SELECT MAX(".$field.") FROM ".$tabel);
$row = mysql_fetch_array($qry);
if ($row[0]=="") {
$angka=0;
}
else {
$angka = substr($row[0], strlen($inisial));
}
$angka++;
$angka =strval($angka);
$tmp ="";
for($i=1; $i<=($panjang-strlen($inisial)-strlen($angka)); $i++) {
$tmp=$tmp."0";
}
return $inisial.$tmp.$angka; }
how to convert this code to php pdo? please help me..
Here is a standard snippet I use for PDO:
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
$date = reformatDate($_POST['date']);
$sql="SELECT * FROM order_items WHERE date_start = :date";
$sth = $dbh->prepare($sql);
$sth->bindParam(':date', $date, PDO::PARAM_STR, 10);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
This example should point you in the right direction, but you need to do the heavy lifting.
Update
This would also be acceptable.
$madeupstring = "Mk9285425";
$sql="SELECT * FROM order_items WHERE product = :whatever";
$sth = $dbh->prepare($sql);
$sth->bindParam(':whatever', $madeupstring);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
You could also do this:
$sql="SELECT * FROM order_items WHERE product = 'Mk9285425'";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$query = $db->prepare("SELECT * FROM coupons WHERE deleted = ? LIMIT ?, ?");
$query->bindValue("1", 0);
$query->bindValue("2", 2);
$query->bindValue("3", 5);
try{
$query->execute();
$result = $query->fetchAll();
return $result;
}catch(PDOException $e){
die($e->getMessage());
}
Unfortunately this returns a result with no rows (but an empty result not even an error), and when I run this sql query through phpmyadmin, it fetches me multiple rows.
Any suggestions would be really be helpful. I can't get through this.
First comment to this question helped me very well: Here
And solved my problem. Al the above suggestions mentioned above were previously tried and did not work.
try to use like this
<?php
$query = $db->prepare("SELECT * FROM coupons WHERE deleted = :deleted LIMIT :limit, :offset");
$query->bindValue(":deleted", 0);
$query->bindValue(":limit", 2);
$query->bindValue(":offset", 5);
try{
$query->execute();
$result = $query->fetchAll();
return $result;
}catch(PDOException $e){
die($e->getMessage());
}
?>
bindValue expects an integer in case of you using a question mark as a binder
and not a string like you provided:
$query = $db->prepare("SELECT * FROM coupons WHERE deleted = ? LIMIT ?, ?");
$query->bindValue(1, 0);
$query->bindValue(2, 2);
$query->bindValue(2, 5);
try{
$query->execute();
$result = $query->fetchAll();
return $result;
}catch(PDOException $e){
die($e->getMessage());
}
or simply do this:
$query = $db->prepare("SELECT * FROM coupons WHERE deleted = ? LIMIT ?, ?");
$binds = array(0,2,5);
try{
$query->execute($binds);
$result = $query->fetchAll();
return $result;
}catch(PDOException $e){
die($e->getMessage());
}
I am new to PHP prepare method, I need some help to use while loop in the following code.
Here is the query function
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt-> execute($bindings);
$result = $stmt->fetchAll();
return $result ? $result : false;
}
and the query
$home_team = query('SELECT home_team FROM premier_league
WHERE match_date >= :current_date
AND pre_selected = :pre_selected
ORDER BY match_date LIMIT 5',
array('current_date' => $current_date,
'pre_selected' =>$pre_selected),
$conn);
if (empty($home_team)){
echo "No Match Selected for Today.";
} else {
print_r($home_team);
}
How and where I use while loop for this query?
you don't need no while here
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt-> execute($bindings);
return $stmt->fetchAll();
}
$sql = 'SELECT home_team FROM premier_league WHERE match_date >= ?
AND pre_selected = ? ORDER BY match_date LIMIT 5';
$home_team = query($sql,array($current_date, $pre_selected), $conn);
foreach ($home_team as $row) {
echo $row['home_team']."<br>\n";
}
In else block
else {
print_r($home_team);
/* here
foreach ($home_team as $team) {
echo $team->home_team . '<br>';
}*/
}
PDOStatement implements Traversable so using fetchAll would be a overhead.
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt;
}
$home_team = query...;
foreach ($home_team as $row) {
echo $row['home_team']."<br>\n";
}
The idea of using a prepared query is to have the server parse the query once and create a query plan once. This is useful for queries that you execute repeatedly, only changing the parameter values.
Accordingly:
- the prepare should be done once.
- the execute should be done inside the loop.
If you are executing a query once in a while, then the prepare overhead is not worth it.
What would i use in PDO instead of old mysql_resul()?
function ib_uk_isvalid($db,$uk) {
try {
$sth = $db->prepare("SELECT count(*) FROM ib_userkeys WHERE value=:val");
$sth->bindParam(":val",$uk);
$sth->execute();
$numrows = $sth->fetchColumn();
if($numrows>=1) {
$sth2 = $db->prepare("SELECT * FROM ib_userkeys WHERE value=:val");
$sth2->bindParam(":val",$uk);
$sth2->execute();
$res = $sth2->fetchAll();
print($res[0]->type);
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
ib_uk_isvalid($db,1234)
Gives me error because it returns table instead of an object (which i need).
function ib_uk_isvalid($db, $uk) {
$query = $db->prepare('SELECT * FROM ib_userkeys WHERE value = :val LIMIT 1');
$query->bindValue(':val', $uk);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
return $row ? $row->type : 0;
}
... is how I'd write that. It may fix the problem.