fetching multiple rows with new mysqli query? - php

I'm using php to connect to mysql database and am using the following function to retrieve multiple rows from database and then add them to an array and send them back. I'm getting internal server error or 500x error messages. I'm not sure what is wrong with this code. I've tried to figure it out but can't get it.
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
if ($stmt->execute()) {
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$resp = array();
while($stmt->fetch()){
$row = array();
array_push($row, $col1, $col2, $col3);
array_push($resp, $row);
}
$msg = array('msgid' => $msgid,'title' => $title,'fromuname' => $fromuname);
$stmt->close();
return $msg;
} else {
$stmt->close();
return NULL;
}
}
how should I go about doing this? The function that handles the returned results are as follows
$app->get('/inbox', 'authenticate', function() use ($app){
ob_start("ob_gzhandler");
global $global_user_name;
$db = new DbHandler();
$resp = $db->getUnreadMessages($global_user_name);
$msgs = array();
$msgs['status'] = 'success';
$msgs['version'] = 0.1;
array_push($msgs, $resp);
$app->response()->header('Content-Type', 'application/json');
echo json_encode($msgs);
exit;
});

The PDO method automating this is $stmt->fetchAll() :D
public function getUnreadMessages($uname)
{
$stmt = $this->conn->prepare("SELECT msgid,title,fromuname FROM messages WHERE touname = ? and status = ?");
$stmt->execute([$uname, 'unread']))
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Return false if nothing has been found or something like :
$msg = [
[
'msgid' => 2746,
'title' => 'Random title',
'fromuname' => 'SomeGuy'
],
[
'msgid' => 754,
'title' => 'Some title',
'fromuname' => 'Random Name'
],
[
'msgid' => 27686,
'title' => 'Unreadable title',
'fromuname' => 'Training dummies'
],
];

I've solved my question. It was that I was creating an array within a loop. This seems to be disallowed. Here's the code that did work in the end
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
$result = $stmt->execute();
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$outer = array();
$inner = array();
while($stmt->fetch()){
array_push($inner, $col1, $col2, $col3);
}
array_push($outer, $inner);
return $outer;
$stmt->close();
}

Related

foreach loop update only last value three times in table

This is a code to update a table with foreach loop. But it update the last value three times which is POST[s3_name]
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
You could get the id from somewhere and loop that as well. Something like this
$names = [
['id' => 1, 'name' => 'name1'],
['id' => 2, 'name' => 'name2'],
['id' => 3, 'name' => 'name3']
];
foreach ($names as $name) {
try {
$query = "update students SET Name=:Name WHERE ProjectID=:Id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name['name']);
$stmt->bindParam(':Id', $name['id']);
$result = $stmt->execute();
$msg = "Record updated";
} catch(PDOException $ex) {
$msg = $ex -> getMessage();
}
}

Function that is supposed to return a value from query

I have this function which I use to get a value from a query. I might be doing something wrong with the execution, or the syntax. When I try to run the query with the data in it, it's fine, but this one returns 0 items.
public function get_modified_event ($type, $id, $employee_id)
{
global $dbh;
$sql =<<<SQL
SELECT outlook_id
FROM dba.events
WHERE spine_item_type = :type
AND spine_id = :id
AND employee_id = :employee_id
SQL;
$stmt = $dbh->prepare( $sql );
$stmt->execute( array(
'id' => $id,
'type' => $type,
'employee_id' => $employee_id,
) );
$rows = $stmt->fetchAll( \PDO::FETCH_ASSOC );
return $rows['outlook_id'];
}
You could try reworking a portion of the code so that it uses this kind of a format:
$stmt = $dbh->prepare( $sql );
if ($stmt->execute( /* your array goes here */ )) {
$rows = $stmt->fetchAll( PDO::FETCH_ASSOC );
if ($rows !== FALSE){
print_r($rows);
}
else
if ( $stmt->rowCount() === 0) {
echo "The info provided is unknown to the database";
}
}
Hopefully you'll get some meaningful results.

How to convert mysqli code to PDO stmt?

if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
// get product details
$query = $db->query("SELECT * FROM products WHERE id = ".$productID);
$row = $query->fetch_assoc();
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
I'm trying to convert this code to PDO stmt. Please help me with this, I'm new here.
You need to develop and pdo connection with whichever database you have. Check the connection check and connect with it.
Make sure that you have install PDO library, check it your php info.
try
{
$conn =new PDO("sqlsrv:Server=$this->hostName;Database=$this->dbName", "$this->userName", "$this->password");
$productID = $_REQUEST['id'];
$sql = "SELECT * FROM products WHERE id=?";
$stmt->bindParam(1, $productID);
$stmt = $conn->prepare($sql);
$this->result = $stmt->execute();
if (!$this->result)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
}
}
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
catch(Exception e)
{
echo $e->getMessage();
exit();
}

Looking for solution to insert PHP array to SQL database by using PDO

This is my array of order detail, array structure will be: "ids" => "qtys":
$orderData = array();
$transactionID = 1;
$orderItems = $_POST['orders'];
//echo json_encode($orderItems);
foreach ($orderItems as $order){
$qtys = $order['qty']; //Which will be "quantity" insert into database;
$ids = $order['id']; //Which will be "itemID" insert into database;
$orderData["$ids"]=$qtys;
}
Now I am looking for solutions to push the array inside the database:
$sql = "INSERT INTO item_transaction (transactionID,itemID,quantity) VALUES ($transactionID,?,?)" ;
How should I continue?
You can use bindParam to insert it inside the loop.
something like...
$stmt = $conn->prepare("INSERT INTO item_transaction transactionID,itemID,quantity) VALUES (:transactionId,:itemId,:qty)");
$stmt->bindParam(':transactionId', $transactionID );
$stmt->bindParam(':itemId', $itemID);
$stmt->bindParam(':qty', $quantity);
foreach ($orderItems as $order){
$quantity = $order['qty'];
$itemID = $order['id'];
$stmt->execute();
}
Unfortunately, you did not provide your DDL and you did not show where some of your data comes from ($transactionID ?).
<?php
class Handler {
public $dbHostname = 'DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE';
public $dbDatabaseName = 'MYSQL-DBNAME-GOES-HERE';
public $user = 'DATABASE_USERNAME';
public $password = 'DATABASE_PASSWORD';
//public $port = 3307;
public $message;
public function handleRequest($arg) {
$orderItems = $arg['orders'];
try {
$portChunk = ( isset($this->port) ) ? ';port=' . $this->port : null;
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname}{$portChunk}";
$pdo = new PDO($dsn, $this->user, $this->password);
$transactionID = 1;
$stmt = $pdo->prepare("INSERT INTO item_transaction transactionID, itemID, quantity) VALUES (?, ?, ?)");
foreach ($orderItems as $order){
$stmt->execute([$transactionID, $order['id'], $order['qty']]);
}
}
catch(PDOException $e) {
$this->log('Failed: ' . $e->getMessage());
}
}
}
// Change the following to false to test from the web.
$commandLine = true;
$handler = new Handler();
if ( $commandLine ) {
// run from command line
$handler->handleRequest(['orders' =>
['qty' => 9, 'id' => 111],
['qty' => 4, 'id' => 222],
['qty' => 11, 'id' => 333],
]);
}
else {
$handler->handleRequest($_POST);
}
Bear in mind that I have NOT tested this code at all. Run it and see what happens.

Convert mysqli to pdo bind_all

here is my current code
function getUserDetails($username=NULL, $id=NULL) {
if($username!=NULL) {
$column = "user_name";
$data = $username;
}
elseif($id!=NULL) {
$column = "id";
$data = $id;
}
global $db;
$query = $db->prepare("SELECT id, username, permissions, forename, surname, password, email, courseid, choiceid, lastlogin, active FROM users WHERE $column = :column");
$query->bindParam(":column", $data);
$query->execute();
$query->bind_result ($id, $username, $permissions, $forename, $surname, $password, $email, $courseid, $choiceid, $lastlogin, $active);
while ($query->fetch()){
$row = array('id' => $id, 'userlevel' => $permissions, 'username' => $username, 'forename' => $forename, 'surname' => $surname, 'password' => $password, 'email' => $email, 'courseId' => $courseid, 'choiceId' => $choiceId, 'lastlogin' => $lastlogin, 'active'=> $active);
}
return ($row);
}
I have been trying to convert this to pdo, as I've found out bind_result doesn't work with pdo - could anyone help me as to what I should be doing?
I've read arround that I should be using fetch? But i'm getting really confused.
[edit]
ive tried this:
function getUserDetails($username=NULL,$id=NULL) {
if($username!=NULL) {
$column = "user_name";
$data = $username;
}
elseif($id!=NULL) {
$column = "id";
$data = $id;
}
global $db;
$query = $db->prepare("SELECT id, username, permissions, forename, surname, password, email, courseid, choiceid, lastlogin, active FROM users WHERE $column = :column");
$query->bindParam(":column", $data);
$query->execute();
$results = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return ($results);
}
is this a step in the right direction ?
[edit2]
updated my code to this:
function getUserDetails($username) {
global $db;
$query = $db->prepare("SELECT * FROM users WHERE username = :username");
$query->bindParam(":username", $username);
return $query->fetch(PDO::FETCH_ASSOC);
}
$username = 'uname';
$result = getUserDetails($username);
print_r($result);
however it prints nothing. the username definitely exists.
ive tried a test database with some dummy data
$data = '2';
$sth = $db->prepare("SELECT * FROM test WHERE id = :id");
$sth->bindParam(":id", $data);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
im trying to figure out how i access what is in the printed array:
the array comes out as
Array ( [Id] => 2 [Name] => tom )
how do i (for example) do
$name = $result['name']; //line 67
when i try that code i get
Notice: Undefined index: name in <directory>\test.php on line 67
Figured it out!
function getUserDetails($username) {
global $db;
$sth = $db->prepare("SELECT id, username, permissions, forename, surname, password, email, courseid, choiceid, lastlogin, active FROM users WHERE username = :username");
$sth->bindParam(":username", $username);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result;
}
$username = 'un';
$userdetails = getUserDetails($username);
echo $userdetails['forename'];
and it gives me the correct answer!
thanks for your help
YES!
It's great step in the right direction.
As you can see, mysqli is absolutely unusable with prepared statements, both in binding placeholders and returning results.
while PDO can solve your problem using dramatically less code.
You don't need useless bind with PDO at all - just get all results with fetchAll():
function getUserDetails($username=NULL,$id=NULL) {
if ($username) {
$column = "user_name";
$data = $username;
} elseif($id) {
$column = "id";
$data = $id;
} else {
return;
}
global $db;
$query = $db->prepare("SELECT * FROM users WHERE $column = ?");
$query->execute(array($data));
return $query->fetchAll();
}
But wait. Why do you want to return an array if it's users details?
It will add just useless dimension to the returned array.
For this very case make it
return $query->fetch();
instead of fetchAll().
But then you need many rows - use this latter method.
On other methods and useful connect options refer to the tag wiki

Categories