mysql_fetch_array showing the first row only when using while loop - php

shortly I'm facing an issue using while loop... I don't know what is going on, So, I thought that I should ask for help, after a lot of searches, I know that mysql_fetch_array returns a row in every time, so we should use while if we need to get all rows from the query.
and after trying to avoid while and use foreach I found that simply we can't use foreach instead of while or we can use it as another loop after while.
anyways, my problem is: I created a stored procedure in mysql database, and it working fine throw my php code using ajax, but when I tried to put it in a loop based on IDs of some data, the while loop gave me the first row only after calculations.
so please if anyone can see what I can't see in the code, don't hesitate.
thanks..
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$thefinalres="";
$loop = mysql_query("SELECT * FROM mrh_chains order by id");
if ($loop){
while ($row = mysql_fetch_array($loop))
{
$theid = $row['id'];
$thename = $row['name'];
//CALL PROCEDURE
$result = mysql_query("CALL calccommission($theid,'$startdate','$enddate')");
if ($result){
$row2 = mysql_fetch_array($result);
if ($row2[0]!=""){
$thecommission = $row2[0];
} else {
$thecommission = "Try to change dates, There are no data on these dates";
}
$thefinalres .= $thename . " commission: ". $thecommission . "<br/>";
}
}
$value = array('msg' => 'true' );
$value["res"] = $thefinalres;
} else {
$value = array('msg' => 'false' );
}

after a looooooooooooooooot of search, I found solution with mysqli
$mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,#x);SELECT #x" );
if( $res ) {
$results = 0;
do {
if ($result = $mysqli->store_result()) {
printf( "<b>Result #%u</b>:<br/>", ++$results );
while( $row = $result->fetch_row() ) {
foreach( $row as $cell ) echo $cell, " ";
}
$result->close();
if( $mysqli->more_results() ) echo "<br/>";
}
} while( $mysqli->next_result() );
}
$mysqli->close();
I found answer in this article: https://forums.mysql.com/read.php?52,198596,198717

Related

PHP SQL server query

I'm running a query to get the contents for a web slider.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"DB", "UID"=>"User", "PWD"=>"PWD" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sliders.DisplayFrom, Sliders.DisplayUntil, Sliders.Sort, Sliders.Image, Sliders.Link, Sliders.Target FROM Sliders WHERE (((Sliders.DisplayFrom)<GetDate()) AND ((Sliders.DisplayUntil)>getdate())) ORDER BY Sliders.sort;";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql);
$maxx = 0;
while($row = sqlsrv_fetch_array($result)) {
$maxx++;
}
while($row = sqlsrv_fetch_array($result)) {
echo “<br>” . $row[‘Image’];
}
The second loop does not output any results. why? Is it because $row is already at the end? If so, how do I move first like in ASP without having to create $result2 and $row2, 3, 4, 5, ...
Would it be better to use for loops like in vb.net?
for ($i = 0; $i <= $maxx; $i++){
}
But then How do I specify the output if I have no $row?
and if I only wanted to output the first row like I do in vb.net, how would I write the following in PHP?
dsqueryResults.tables(0).rows(0).item("Image");
would I still use a while loop and have a variable inside the loop to hold the row number and only output if row = 0?
$WhichRow = 0;
while($row2 = sqlsrv_fetch_array($result2)) {
if ($whichRow == 0){
echo “<br>” . $row2[‘Image’];
}
$WhichRow++;
}
Use the $max++ counter inside the while loop if you really want to use that for other purposes.
If you just want a count then run a count query on MySQL or do an array count of returned result.
If you just want to print 1 row use
LIMIT 0,1
at the end of your query as there's no point in fetching all rows and waste resources.
Based on additional comments you can try this to get your current row number.
$result = sqlsrv_query($conn, $sql);
$rownumber = 0;
while($row = sqlsrv_fetch_array($result)) {
$rownumber = $rownumber + 1;//Your current row number.
echo “<br>” . $row[‘Image’];
}

WHERE clause with empty string doesn't return any rows

I have an iOS app which I built an API to extract some data from a SQL Server database. When my app sends a query with an empty string, it doesn't return any rows, even though it should.
$connectionInfo = array( "Database"=>db, "UID"=>$user, "PWD"=>$pass);
$conn = sqlsrv_connect($ip, $connectionInfo);
if ( $conn ) {
//connected
}
else {
echo "Error:"; echo "<br>";
die( print_r( sqlsrv_errors(), true));
}
/**************************************/
/* RETRIEVAL */
/**************************************/
$prod = new StdClass(); $arr = array(); $temp = array();
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
$stmt = sqlsrv_prepare( $conn, $sql, array($search));
sqlsrv_execute( $stmt );
$i = 0;
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
else {
while ( $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
$newProd = clone $prod;
$newProd->mainInfo = $row['name'];
$newProd->secondInfo = $row['qty'];
$arr[] = $newProd;
}
}
http_response_code(200);
echo json_encode($arr);
sqlsrv_close($conn);
I built the API with PHP and Apache on macOS where it worked as intended. When I copied the files on a Windows server, if my app accessed a link similar to 192.168.0.102/file.php?search= it would return no rows on Windows, and in macOS it would return all the rows of the table, as I wanted to. I know the script works and there are no issues, because if my app accesses a link similar to 192.168.0.102/file.php?search=someName it returns the corresponding rows. I want the app to display all the rows if the variable search is empty. Should I use some other way to achieve this, or is it some mistake on my part.
you can achieve that by not using sql condition when "search" $_GET param is not supplied or is empty.
Example how to achieve that, change your code from:
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
to something like this:
$search = null;
if (true === array_key_exists('search', $_GET) && false === empty($_GET['search'])) {
$search = '%' . $_GET['search'] . '%';
}
$sql = "SELECT name, qty FROM table";
if (false === is_null($search)) {
$sql .= ' WHERE name LIKE ?';
}

all retrieve data from ms accesss database in php

Data retrieve from the ms access database 2007 in php using odbc driver. ALL data retrieve using query but its get only one record retrieve other data is not retrieve.
below query three records but its retrieved only one data. which problem below code in php?how get all data using query from this code what's changes it?
<?PHP
include 'Connection2.php';
$sql = "select FYearID,Description,FromDate,ToDate from mstFinancialyear";
$stmt = odbc_exec($conn, $sql);
//print_r($stmt);
$rs = odbc_exec($conn, "SELECT Count(*) AS counter from mstFinancialyear");
//print_r($stmt);
$arr = odbc_fetch_array($rs);
$arr1 = $arr['counter'];
$result = array();
//print_r($arr);
if (!empty($stmt)) {
// check for empty result
if ($arr1 > 0) {
// print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$year = array();
$year['FYearID'] = $stmt1['FYearID'];
$year['Description'] = $stmt1['Description'];
$year['FromDate'] = $stmt1['FromDate'];
$year['ToDate'] = $stmt1['ToDate'];
// success
$result["success"] = 1;
// user node
$result["year"] = array();
array_push($result["year"], $year);
echo json_encode($result);
//return true;
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
echo json_encode($result);
}
odbc_close($conn); //Close the connnection first
}
?>
You return only a single record in the JSON data because you do not iterate through the recordset. Initially I misread that you had called odbc_fetch_array twice on the same recordset but upon closer inspection see that one query is imply used, as far as I can tell, to see if there are any records likely to be returned from the main query. The re-written code below has not been tested - I have no means to do so - and has a single query only but does attempt to iterate through the loop.
I included the count as a sub-query in the main query if for some reason the number of records was required somehow - I don't think that it is however.
<?php
include 'Connection2.php';
$result=array();
$sql = "select
( select count(*) from `mstFinancialyear` ) as `counter`,
`FYearID`,
`Description`,
`FromDate`,
`ToDate`
from
`mstFinancialyear`";
$stmt = odbc_exec( $conn, $sql );
$rows = odbc_num_rows( $conn );
/* odbc_num_rows() after a SELECT will return -1 with many drivers!! */
/* assume success as `odbc_num_rows` cannot be relied upon */
if( !empty( $stmt ) ) {
$result["success"] = $rows > 0 ? 1 : 0;
$result["year"] = array();
/* loop through the recordset, add new record to `$result` for each row/year */
while( $row=odbc_fetch_array( $stmt ) ){
$year = array();
$year['FYearID'] = $row['FYearID'];
$year['Description'] = $row['Description'];
$year['FromDate'] = $row['FromDate'];
$year['ToDate'] = $row['ToDate'];
$result["year"][] = $year;
}
odbc_close( $conn );
}
$json=json_encode( $result );
echo $json;
?>

can't get result from sp into array

I'm trying to get the result of a stored procedure in MySQL into an array with use of php. The code I have:
function get_all_uzovi($dbc) {
//$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
// FROM tbl_diagnoses
// WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
// ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,"CALL spGetUzovi");
//WHAT DOES NOT WORK:
//$data = array();
//while ( $row = $result->fetch_assoc() ) {
// $data[] = $row;
//}
//return json_encode($data);
//WHAT DOES WORK:
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
}
The code under "//WHAT DOES NOT WORK" is what I need: the result as a json format. For some reason it gives me nothing..
The code under "//WHAT DOES WORK", does work, but this is not what I want.
the code for the sp:
CREATE DEFINER=`ziekenh3`#`localhost` PROCEDURE `spGetUzovi`()
NO SQL
SELECT *
FROM tbl_uzovi
the code that I use when working with queries (which does work) instead of sp:
function get_diagnoses($dbc,$var_chosen_specialism) {
$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
FROM tbl_diagnoses
WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,$query);
$data = array();
//while ( $row = $result->fetch_assoc() ) {
while ( $row = mysqli_fetch_assoc($result) ) {
$data[] = $row;
}
return json_encode($data);
}
Any thoughts?
Does this work?
function get_all_uzovi($dbc) {
$result = mysqli_query($dbc,"CALL spGetUzovi");
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
return json_encode($data);
}
I Solved it. A bit of a stupid problem: there where some fields in the result set that contained characters like: , ( . etc. I don't think json likes this..
When I did a SELECT * FROM on another table it worked. So, my code that works now is:
function get_all_uzovi($dbc) {
$q = "CALL spGetUzovi";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
return json_encode($data);
}
I'm sorry for the inconvenience!

Program not doing update in ForEach Loop

I am trying to update a file OPPSHEDT with a priority and reason code. It seems the code gets stuck in the foreach loop. It gets to SQL with the Count I get the echo of the selstring on my browser then I do not get the echo of $Count and the update is not done. I'm not quite sure if I'm not connecting and doing the actual SQL on the Count or not. Is there anyway to tell what is going on here?
<?php
require_once ('C:/wamp/db/login.php');
// Try to connect to database
try
{
$db = new PDO($db_hostname, $db_user, $db_pass);
}
catch (PDOExcepton $e)
{
echo $e->getMessage();
exit();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (is_array($_POST['line']))
{
$ohord = $_POST['shedord'];
$ohbord = $_POST['shedbord'];
$date1 = $_POST['sheddat'];
$type = $_POST['shedtyp'];
$prty1 = $_POST['shedpty'];
$resn1 = $_POST['shedrsn'];
foreach($_POST['line'] as $line_no)
{
$type1 = $type[$line_no];
$type2 = substr($type1, 0, 1);
$selstring = "Select Count(*) From LPCUSTTST.OPPSHEDT where sheddat = '$date1[$line_no]' and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring;
$s = $db->prepare("$selstring");
$s->execute();
echo $Count;
if($Count > 0)
{
// Update data into detail
$selstring1 = "UPDATE LPCUSTTST.OPPSHEDT SET SHEDPTY = '$prty1[$line_no]', SHEDRSN = '$resn1[$line_no]' where sheddat = $date1[$line_no] and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring1;
$s = $db->prepare("$selstring1");
$s->execute();
}
}
}
?>
Thank You
Your first SQL statement contains date1[$line_no] while your second contains $date1[$line_no]. You can make things much easier (and safer) by using parameterized queries instead.
Edit: You modified your post to include the missing dollar sign but my suggestion to use parameterized queries still stands.
$selstring = 'SELECT COUNT(*) as total
FROM LPCUSTTST.OPPSHEDT
WHERE sheddat = :sheddat
AND shedtyp = :shedtyp
AND shedord = :shedord
AND shedbord = :shedbord';
$stm = $db->prepare($selstring);
$stm->execute(
array(
'sheddat' => $date1[$line_no],
'shedtyp' => $type2,
'shedord' => $ohord[$line_no],
'shedbord' => $ohbord[$line_no]
)
);
I do not get the echo of $Count and the update is not done
In your code you do echo $Count; but $Count is never defined. You need to fetch the value (I added total to the above SQL):
$row = $stm->fetch(PDO::FETCH_ASSOC);
$count = $row['total'];

Categories