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’];
}
Related
I pull data from the mssql database. I want to assign the data I have captured as an array. So I want to assign more than one table value to the result. Currently, it only assigns 1 value. When I make $ results [], I can't print. I converted it to an array so I can assign more than one data, but it doesn't work.
<?php
...
$conn = sqlsrv_connect( $serverName, $connectionInfo );
$sql = "...";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results = Array("destekcevap_.." => $destekCevap, "destekCevapFoto" => $destekCevapFoto);
}
echo json_encode($results);
sqlsrv_free_stmt($stmt);
?>
Initialize the array above the while-loop and assign new values in the loop like this:
$results = array();
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results[] = "your values";
}
Cheers,
Niklas
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;
?>
I'm using the sqlsrv extension for php and have a problem with fetching the rows from a simple query.
My query is a select which should return 133228 rows but when trying to display the rows I get only 15.
I've searched for an answer but couldn't find a solution and this is my first time using this extension. I've found an answer to a previous question about the same problem but in that case the problem was double calling of sqlsrv_fetch_array, which I don't have for sure.
Here is my query:
$sql = 'select * from ViewProduct';
$params = array();
$options = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query($dbRemote, $sql, $params, $options);
$count = sqlsrv_num_rows($stmt);
if ($count === false)
echo "Error in retrieveing row count.";
else
echo $count;
//$rows = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
print_r($row);
echo "<br>";
//$rows[] = $row;
}
As I said the above query returns 15 when should be 133228 rows.
What am I missing?
Thank you in advance.
i have same problem,
this is my solution for this
$data = [];
$result_num = false;
// get rows num if have any
$result_count_res = sqlsrv_query(
$conn,
$query,
[],
[ "Scrollable" => SQLSRV_CURSOR_KEYSET ]
);
if( $result_count_res === false) {
echo "Row count false";
}else{
// set row num
$result_num = sqlsrv_num_rows( $result_count_res );
}
if($result_num){
// run another query to retrive results
$result_res = sqlsrv_query(
$conn,
$query,
[],
[ "Scrollable" => SQLSRV_CURSOR_FORWARD ]
);
if( $result_res === false) {
// get errors from query
die( print_r( sqlsrv_errors(), true) );
}else{
// run through "for" loop to retrive all results
for($i = 0; $i < $result_num; $i++){
$data[] = sqlsrv_fetch_array( $result_res, SQLSRV_FETCH_ASSOC);
}
}
sqlsrv_free_stmt( $result_res );
}else{
echo "Row count false";
}
echo '<pre>';
var_dump($data);
echo '</pre>';
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
**Edited for more info
I'm having issues creating a search page to display results from a SQL Server database. My SQL is correct because it outputs what I want in SSMS. My connection info is also correct as I've tested that. My issue is coming from tying it into the search form - I can't get it to find any results. If I want it to print a table it prints just fine, however, I really need this to work as a search. I'm still pretty new at PHP and SQL in general but this is what I have so far:
$serverName = "myserver";
$connectionInfo = array( "Database"=>"mydb", "UID"=>"myuser", "PWD"=>"mypass");
$conn = sqlsrv_connect( $serverName, $connectionInfo) OR die ('broke:' .sqlsrv_errors());
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = sqlsrv_query($conn, "SELECT columns_I_need
FROM tables_I_need
WHERE col_1 LIKE '%$searchq%'") or die('broke:' .sqlsrv_errors());
$count = sqlsrv_num_rows($query);
if($count == 0) {
$output = 'There was nothing';
} else {
while($row = sqlsrv_fetch_array($query)) {
$stname = $row['streetname'];
$stno = $row['streetnumber'];
$apno = $row['permitnumber'];
$output .= '<div> '.$stname.' '.$stno.'</div>';
}
}
}
My search form looks like this:
<form> action="" method="post">
<input type="text" name="search" placeholder="Search for address...">
<input type="submit" value="Submit">
</form>
<?php print("$output"); ?>
Every time I search I get no results. So I guess my question is: is my search form correct and is my WHERE col_1 LIKE '%$searchq%' correct? What am I missing? Also, does the preg_replace not help in preventing sql injection?
If this isn't descriptive enough, please let me know.
I think the problem is to do with this line:
$count = sqlsrv_num_rows($query);
From the documentation for sqlsrv_num_rows() on php.net (emphasis mine).
Parameters
The statement for which the row count is returned. The statment resource must be created with a static or keyset cursor.
Parameters - sqlsrv_num_rows
and
Return Values
Returns the number of rows retrieved on success and FALSE if an error occurred. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.
Return Values - sqlsrv_num_rows
Because you have failed to specify a cursor in your query, the default cursor is used and false is returned, regardless if the query had returned results.
Then in your if statement, you check $count == 0. This check will return true, as 0 can be evaluated to false and you are not using strict type comparison (===). Therefore you will always see "There was nothing".
To fix this, you will need to specify a static or keyset cursor for your query. I'm going to use SQLSRV_CURSOR_STATIC as my cursor as an example, but you could use SQLSRV_CURSOR_KEYSET. See here for more information about the different cursors.
The general syntax is:
$stmt = sqlsrv_query($conn, $query, $params, array("Scrollable" => SQLSRV_CURSOR_STATIC));
I think I have this nailed down. It displays everything I need, I believe it's set up as a parameterized query, and with my class tags I'm able to style the output.
My only issue is if someone enters the street number AND the street name or the street name is two or more words, I don't get any results. It's probably something simple with my $sql statement. I tried:
WHERE (STNO LIKE '%$search_term%' AND STNAME LIKE '%$search_term%') OR APNO LIKE '%$search_term%'
but that doesn't get me anything either.
$serverName = "myserver";
$connectionInfo = array( "Database"=>"mydb", "UID"=>"myuser",
"PWD"=>"mypass");
$conn = sqlsrv_connect( $serverName, $connectionInfo) OR die ('broke:'
.sqlsrv_errors());
$search_term = $_GET['query'];
$sql = "SELECT my rows FROM my tables
WHERE STNO LIKE '%$search_term%' OR STNAME LIKE '%$search_term%' OR APNO LIKE '%$search_term%'
ORDER BY STNO";
echo "<div class='search-term-display'>You searched for: ", $search_term, "</div>";
if(isset($_GET['query'])) {
$search_term = $_POST['query'];
$search_term = preg_replace("#[^0-9a-z]#i", "", $search_term);
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => 'static'));
while($data = sqlsrv_fetch($query)) {
while($row = sqlsrv_fetch_array($query)){
$stno = $row['STNO'];
$stname = $row['STNAME'];
$apno = $row['APNO'];
$suffix = $row['SUFFIX'];
$hseptyp = $row['HSEPTYP'];
$dttm = $row['COMPDTTM']->format('d/m/Y');
$partial = $row['PARTIAL'];
$waived = $row['WAVIED'];
$failed = $row['FAILED'];
$inspcomments = $row['INSPECTIONCOMMENTS'];
$fcomments = $row['FAILEDCOMMENTS'];
$descript = $row['DESCRIPT'];
echo "<hr>";
echo "<div class='insp_address'>".$stno.' '.$stname.' Permit Number: '.$apno."</div>";
echo "<div class='insp_date'>".'Inspection Date: '.$dttm."</div>";
echo "<div class='sys_type'>".'Septic System Type: ' .$hseptyp."</div>";
echo "<div class='code_violation_status'>".'Code Violation Status: ' .$descript."</div>";
echo "<div class='code_violation'>".'Code: '.$failed."</div>";
echo "<div class='insp_comments_title'>Inspection Comments:</div>";
echo "<div class='insp_comments'>".$fcomments."</div>";
}
sqlsrv_free_stmt( $query);
}
}
echo "</div>";
This is how I used the query and fetch with keyset:
$this->result = SQLSRV_QUERY($this->conn, $this->sql, Array(), Array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
SQLSRV_FETCH($this->result,SQLSRV_SCROLL_RELATIVE,$this->offset);
for($row = 1; $row <= $this->items_per_page; $row++) {
$rows[] = SQLSRV_FETCH_ARRAY($this->result);
}
return $rows;
Then you can use foreach like this:
<?php foreach ($result as $rows) {
if ($rows != NULL) { ?>
<tr>
<td><?php echo $rows['TerritoryID']?></td>
<td><?php echo $rows['TerritoryDescription']?></td>
<td><?php echo $rows['RegionID']?></td>
</tr>
<?php } ?>
<?php } ?>
Forgot to add a good rowcount block:
Function get_total_rows() {
$row_count = SQLSRV_QUERY($this->conn, $this->sql, Array(), Array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
return SQLSRV_NUM_ROWS($row_count);
SQLSRV_FREE_STMT($row_count);
}