I am unable to get the following working. I want to use prepared statements in the example below, but I am getting an error. The function defnitily gets passed the correct value in $array:
private function getInfoFromSystem($array) {
try {
$sql = "
SELECT
PCO_AGENT.NAME,
PCO_INBOUNDLOG.LOGIN AS LOGINID,
PCO_INBOUNDLOG.PHONE AS CALLERID,
PCO_INBOUNDLOG.STATION AS EXTEN,
PCO_INBOUNDLOG.TALKTIME AS CALLLENGTH,
PCO_INBOUNDLOG.CHANNELRECORDID AS RECORDINGID,
PCO_SOFTPHONECALLLOG.RDATE,
PCO_INBOUNDLOG.RDATE AS INBOUNDDATE
FROM
PCO_INBOUNDLOG
INNER JOIN
PCO_LOGINAGENT ON PCO_INBOUNDLOG.LOGIN = PCO_LOGINAGENT.LOGIN
INNER JOIN
PCO_SOFTPHONECALLLOG ON PCO_INBOUNDLOG.ID = PCO_SOFTPHONECALLLOG.CONTACTID
INNER JOIN
PCO_AGENT ON PCO_LOGINAGENT.AGENTID = PCO_AGENT.ID
WHERE
LOGINID = :extension
";
$arr = array(":extension" => $array['extension']);
$query = $this->mssql->prepare($sql);
$query->execute($arr);
// $sql = "select * from sys.messages where message_id = 229";
foreach($this->mssql->query($sql) as $row) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
You should not be calling query() after execute(). Instead you need to fetch() your rows:
$query = $this->mssql->prepare($sql);
$query->execute($arr);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
// OR rather than the fetch loop above, use fetchAll()
$rowset = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);
In my experience with PDO + MSSQL, attempting to call a regular query immediately after calling execute() on a statement that returns rows will fail unless you have called $query->closeCursor() first. However, in this case, you should not be calling query() at all. You've already executed your statement with bound params, and just need to fetch rows from it.
Related
I know how to use fetch_array instead of printf() function when expressing rows from database using mysqli bind function.
How can I use $row->mysqli_fetch_array and then use $row[0],$row[1] instead of using the printf() function every time I want to print something from database?
Returning an associative array from a prepared statement you can follow up the procedure like this as follows.
<?php
$category = $_POST['category'];
$sql = "select id, name from items where category = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $category);
if($stmt->execute())
{
$result = $stmt->get_result();
$a = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
}
else
{
error_log ("Didn't work");
}
?>
You can use while loop for printing up the value over from the associative array.
while($a = $result->fetch_array(MYSQLI_ASSOC))
{
echo 'Id: '. $a['id'];
echo '<br>';
echo 'Name: '.$a['name'];
}
Output:
Id: 1
Name: Example
If I got your question correctly you can try:
$row=mysqli_fetch_array($result,MYSQLI_NUM);
foreach($row as $cell) {
echo "$cell";
}
A very nice person on this site helped me with the following script (and it worked a treat)
<?php
$db = new PDO('mysql:host=HOST;dbname=DATABASE', $user, $pass);
$stmt = $db->prepare('
SELECT
yeast,
rating,
description,
weblink,
image,
sideimage
FROM dowdb_yeast_selector
WHERE
fruit = :fruit
ORDER BY
rating DESC
');
$stmt->bindParam(':fruit',$_POST['fruit'],PDO::PARAM_STR,50);
$stmt->execute();
How do I just echo side image (not as part of a while loop)?
I think (?) I need something like echo '$row[sideimage]' // how simple am I
All of the examples I have looked at so far do not fit my needs :-(
Use PDO::fetchAll, for example;
$stmt->execute();
$arrResults = $stmt->fetchAll();
//$arrResults will be multidimensional
//This will echo the first sideimage
echo $arrResults[0]['sideimage'];
If you want to echo all values of sideimage (ie: all rows), you'd have to iterate through the results;
foreach($arrResults as $arrRow) {
echo $arrRow['sideimage'] . PHP_EOL;
}
Links
pdo::fetchAll
You should use loop pdo::fetch()
while($abc = $stmt->fetch())
{
print_r($abc);
}
If you don't want to use loop try pdo::fetchAll()
$data = $stm->fetchAll();
You could use FETCH_ASSOC
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $res[0]['sideimage'];
or
foreach($res as $key=>$value) {
$image_val = $value['sideimage'];
}
I'm trying to echo out 10 numbers from my database in descending order sort of like a Highscores table.
This is my code
$conn = new PDO("mysql:host=HOST;dbname=NAME", "NAME", "PASSWORD");
$hs = $conn->query("SELECT exp FROM login ORDER BY number DESC LIMIT 10");
<? echo $hs?>
I'm new to PDO/PHP I didn't get any errors it just doesn't print anything from my table its just blank ;/
you have to fetch the results in a array, and then echo the elements of the array.
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() fetch the results and echo.
if($numbers = $stmt->fetchAll(PDO::FETCH_ASSOC)) //This will fetch all results in associative array.
{
//If the array contained data, then echo them.
foreach ($numbers as $num)
{
echo $num['exp'] . "<br />";
}
}
else
{
//If the PDOStatement returned an empty array. Let us know.
echo "No data in the array";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
In queries that return large results I wouldn't use $stmt->fetchAll().
I would use fetch in a while loop like this:
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() !!!ECHO WHILE FETCHING!!!
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) //This loop will keep going for as many rows as the PDOStatement returns.
{
echo $row['exp'] . "<br />";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
The difference between the first code chunk and the second is that in 1st chunk, we fetch all the results in a array and print them. In the second one tho, we print the data as we retrieve them one by one with PDOStatement::fetch()
You need to fetch the data from the object. I'll provide a link rather than code that will be helpful to you.
It should give you good introduction. It covers your question.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_Select_Statements
If I do this in PHP, it works fine and loops as expected:
$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs)){
writeme("UserID: " . $row["UserID"]);
}
But I keep wanting to abstract this out into a function I have called ExecuteQuery:
function ExecuteQuery($sql){
$result = mysql_query($sql);
if ($result) {
if($result != 1){
return mysql_fetch_assoc($result); // return recordset
}
}else{
$message = 'Invalid query: ' . mysql_error() . "<br>";
$message .= 'Whole query: ' . $sql;
echo $message;
die();
}
}
This function works great in 2 out of 3 scenarios:
1- Works great for a query that returns 1 row, and I can access like this:
$rs = ExecuteQuery($sql);
$foo = $rs["UserID"];
2- Works great for a sql statement that returns no records, like an UPDATE or DELETE.
3- But when I try to get back a recordset that returns multiple records, and then loop through it, I get an infinite loop and my browser crashes. Like this:
$rs = ExecuteQuery($sql);
while ($row = $rs){
writeme("UserID: " . $row["UserID"]);
}
How can I modify my while loop so it advances to each new record in the recordset and stops after the last record? I'm sure it's a dumb little thing, but I'm not expert with PHP yet. I'd really like my ExecuteQuery function to be able to handle all 3 scenarios, it's very handy.
try foreach($rs as $row){ instead of while ($row = $rs){
mysql_fetch_assoc() only returns one row of the result. To get the next row, you need to call mysql_fetch_assoc() again. One thing you could do is have your ExecuteQuery function return an array of arrays:
$rows = array();
while ($row = mysql_fetch_assoc($result) !== false) {
$rows[] = $row;
}
return $rows;
Also, you should not use the mysql_* functions as they are deprecated. Try using PDO or mysqli_* instead.
Don't use while, use foreach:
$rs = ExecuteQuery($sql);
foreach ($rs as $row){
writeme("UserID: " . $row["UserID"]);
}
I have called a MySQL stored procedure from PHP using mysqli. This has one out parameter.
$rs = $mysqli->query("CALL addNewUser($name,$age,#id)");
Here, #id is the out parameter. Next, I fire the following query to get the value of the out parameter:
$rs2 = $mysqli->query("SELECT #id");
while($row = $rs->fetch_object()){
echo var_dump($row);
}
The output of var_dump is as follows.
object(stdClass)#5 (1) { ["#id"]=> string(6) "100026" }
So, now I want to retrieve the value of #id, which I am unable to. I tried $row[0]->{#id} but this gave following error:
PHP Fatal error: Cannot use object of type stdClass as array
Or even just do a "SELECT #id AS id" then $row->id will work fine. I always rename select columns to keep the name meaningful when necessary :-)
BTW, you can simply concatenate the call and select #... (with a ; statement delimiter) and the RS will be the returned value. Unfortunately this returns a mutli-resultset and you need to flush the full set otherwise the subsequent queries will stall. See following examples:
$db->multi_query( "CALL addNewUser($name,$age,#id);SELECT #id as id" );
$db->next_result(); // flush the null RS from the call
$rs=$db->store_result(); // get the RS containing the id
echo $rs->fetch_object()->id, "\n";
$rs->free();
Alternatively add the select into the addNewUser and return a RS instead of out param
$rs = $db->query( "CALL addNewUser($name,$age)" );
echo $rs->fetch_object()->id, "\n";
$rs->close();
$db->next_result(); // flush the null RS from the call
The first returns a multiquery (NULL, RS) set and the second a (RS, NULL) set, hence you can use a simple query() call which embeds the first fetch_object(), but you still need to flush the RS stack.
Just $row->{"#id"} would work here. You can't use an stdClass as an array ($row[0]...).
Alternatively, you can just fetch the data as an array using mysqli::fetch_assoc() and access the data using $row['#id'].
Another correct methods its working fine: Cheers!!
$procedureName = 'VALIDATE_USER';
$procedure = "CALL $procedureName('$username','$pwd',#p_userid)";
$results1 = $dbconnection->query($procedure);
$results2 = $dbconnection->query("SELECT #p_userid");
$num_rows = $results2->num_rows;
if ($num_rows > 0) {
while($row = $results2->fetch_object())
{
echo $row->{"#p_userid"};
}
}
Here is the working solution:
enter code $res = $conn->multi_query( "CALL PROCNAME(#x);SELECT #x" );
if( $res ) {
$results = 0;
do {
if ($result = $conn->store_result()) {
printf( "<b>Result #%u</b>:<br/>", ++$results );
while( $row = $result->fetch_row() ) {
foreach( $row as $cell ) echo $cell, " ";
}
$result->close();
if( $conn->more_results() ) echo "<br/>";
}
} while( $conn->next_result() );
}
$conn->close();