The mysql fetch results are empty if I retrieve all rows - php

I'm having some issues returning values from a server with php + mysql.
This is my code
$result = mysql_query("SELECT * FROM Nicknames", $con);
if (mysql_real_escape_string($_POST['Create']) == "NICKNAME") {
$output;
while ($row = mysql_fetch_assoc($result)) {
if ($row['Taken'] == '0') $output = $output . $row['Nickname'] . ",";
}
echo substr($output, 0, -1);
}
If I add break; in the while loop, it works perfectly and I just get 1 row of my table.
If instead I want to return all 3000 rows, I just get an empty answer from the server.
If the table has 10 rows it works.
I was wondering if it is about the amount of rows, or it is because eventual special characters.
thanks
UPDATE
It works until 1330 rows, if I try to get more, I get an empty result
$counter = 0;
while ($row = mysql_fetch_assoc($result)) {
if ($row['Taken'] == '0') $output = $output . $row['Nickname'] . ",";
if ($counter == 1330) break;
$counter++;
}
echo substr($output, 0, -1);

Somewhere in the middle of your table's rows there may have been an invalid character.
Since you know which row it stops working at, try running the SELECT with different ORDER BY's to determine if this is the case. :)

Have you tried showing error messages?
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', true);
It is possible that $output is filling the memory_limit before getting to your echo, and if display_errors is false, you won't see the error stating out of memory.

Maybe it's too obvious, but ...
Have you checked the max_execution_time value in your php.ini ?
Maybe the script is dying before finishing the 3000 rows fetch.
Try setting
set_time_limit(0);
at the beginning of the script to avoid this problem

$output after the if condition should be $output = "";

Related

PHP + MySQL suddenly stops the query

I can't understand how and why my mysql_query command stops it's execution.
There are two arrays I work with:
routersTree (includes about 100 rows)
dates (includes about 30 cells)
Here the code:
while ($i <= count($routerTree)){
$currentRouter = $routerTree["router_$i"];
echo "<td>$i</td>";
for ($j = 0; $j < count($dates); $j++) {
$sql = "SELECT indications.id_device FROM indications LEFT JOIN routers ON indications.id_device = routers.id_device WHERE routers.id_router = $currentRouter[id_router] AND date(indications.dateField) = '$dates[$j]' ORDER BY routers.id_device";
if ($res = mysql_num_rows(mysql_query($sql))) {
echo "<td>$res</td>";
}
else {
echo "<td>error</td>";
}
}
}
It stops my cycle after 18-th row, but there are about 82 cycles more to do.
My guess is, that there is a small timeout for mysql_query command.
Any help would be appreciate.
Well, after continue finding the solution of my problem I finaly found one. So easy and so fast... The problem was in PHP timeout. I just added into my settings.php file next entry:
ini_set ('max_execution_time', 0);
The default value is 30 seconds. 0 means the infinite loop. But be careful with this thing. Rise the value for your needs, but try not to use infinite loop.

odbc query returns the first row twice then returns the rest normally

I am querying a database with an odbc connection through php. When I query the db it returns the first row twice and then the rest of the rows the correct amount of times.
Example query:
$stm = SELECT[sUsername] FROM [dbo].[Abilis].[Users] WHERE sUsername = ?;
$pstm = odbc_prepare($conn, $stm);
$exc = odbc_execute($query, array($Username));
I have also tried using DISTINCT but that has not worked either.
EDIT:
for($i=0; $i<odbc_num_rows($pstm);$i++){
$row = odbc_fetch_array($pstm, $i);
if($row['OnCreditHold'] == '1'){
$out = '<button style="color:red;margin:0 auto;" class="btn" onclick="'.'window.location.href='."'information.php?info=".$row['Account_no'];
$out .= "'".'">'.$row['Name'].'</br>';
$out .= $row['Del_ad1'].'</button>';
}
else{
$out = '<button class="btn" style="margin: 0 auto;" onclick="'.'window.location.href='."'information.php?info=".$row['Account_no'];
$out .= "'".'">'.$row['Name'].'</br>';
$out .= $row['Del_ad1'].'</button>';
}
echo $out;
}
You have checked the query result is good outside of this app -- good for you. That means the problem is your loop structure, or maybe your method of getting the data such as odbc_fetch_array().
I ran into this problem once, and I can't recall the solution. I had to try alternative methods to isolate the cause.
For example, instead of for (), try foreach ($elems as $elem) { ... }.
Of course, simplify all the other aspects while you are trouble-shooting. For example, remove the if() structure.
The use of the function odbc_fetch_array ($pstm, $i) with the second parameter starting with zero causes the problem. When you use 0, and the second time 1, it will give you the same result. You could use a while-loop instead of a for-loop and don't use the second parameter.
while ($row = odbc_fetch_array($result))
{
// do something
}

PHP link only passing part of a mysql result

OK i have a php link which is made up of several variables
<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>
The whole code is really long as it has a lot of pagination, so i will just include the basic query and the loop part.
$query1 = "SELECT Distinct model_type from $tableName where manufacturer='$manufacturer' AND fuel='$fuel_type' LIMIT $start, $limit";
$result = mysql_query($query1);
And then the bottom part where i get and show the results.
$count = 0;
$max = 2;
while($row = mysql_fetch_array($result))
{
$model_type = $row['model_type'];
$count++;
echo '<td class="manu"><div align="center">'.'<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>'.'</div></td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
now this works fine except when i take the mode type variable from the database it shows as 1 series, however when it is passed in this link it only gets the 1 and doesn't pick up the series.
Thanks
try to pass it like:
'.urlencode($model_type).'
Try To access it on next page with urldecode($_REQUEST['$model_type'])
I am not shure but you probably have a missing encoding Problem.
try this:
'.$model_type.'
Its url_encoding the values so your url doesnt get broken by ',",spaces and so on.
additional Hint:
Enclose your URL with " or ' so you do not get problems at the end.

replace fetchAll by fetch to avoid memory limit

I run into a memory limit error using fetchAll so I'm trying to use fetch instead but I can't find a way to do it. Any suggestion? Where/How to use the while instead of foreach ?
here is the original code:
// We get all the data from the table
$Qselect = $pdo->prepare('SELECT * FROM '.$table_to_export.'');
$Qselect->execute(array(''));
$results = $Qselect->fetchAll(PDO::FETCH_ASSOC); // Here is the problem
$countRmain = $Qselect->rowCount();
// We get the column names
$Qdescribe = $pdo->prepare('DESCRIBE '.$table_to_export.'');
$Qdescribe->execute();
$limit = $Qdescribe->rowCount()-1; // Number of column in the table
$table_fields = $Qdescribe->fetchAll(PDO::FETCH_COLUMN); // No problem here
foreach($table_fields as $key => $fields){
$outputCsv .= trim($fields).';';
}
// We remove the ; at the end
$outputCsv = rtrim($outputCsv, ';');
// Data
$outputCsv .= "\n";
if($countRmain > 0){
foreach($results as $row){
$column = 0 ;
foreach ($row as $key => $val){
if (is_null($val)){
$outputCsv .= 'NULL;'; // If the field id empty, we add NULL
}
else {
$outputCsv .= $val.';'; // We add the value in the file
}
if ($column == $limit)
$outputCsv .= "\n";
$column ++;
}
}
}
else
exit('No data to export');
I tried to include the foreach loop into while($results = $Qselect->fetch()){ but that takes a really long time (10min for 50000 rows)
PS: If I increase the PHP memory_limit it works with fetchAll but I don't want this solution.
Try this one.
1. comment line 4
2. Replace line 23:
while($row = $Qselect->fetch(PDO::FETCH_ASSOC)){
3. Skip (or Replace) checks on line 22
Idea is simple: u got $result earlier, but not loading whole array. You just step-by-step loading records. That cant be slow enough even for 1M rows becouse u replace one piece of code iterations loop for another same code iterations.
If u still got time problems, try reorganize\optimize your code.
I have also encounter this problem.
Increase the following variables so that your page execution will not stop:
max_input_time
memory_limit
max_execution_time
or you can use
while($row = $Qselect->fetch(PDO::FETCH_ASSOC)){
in place of fatchAll

How to get number of rows with Advantage PHP Extension?

How can I get the number of rows from a SELECT statement result set using the Advantage Database PHP Extension?
I ended up writing my own function that works similar to mysql_num_rows:
function my_num_rows($result) {
ob_start(); // begin disable output from ads_result_all
(int)$number = ads_result_all($result);
ob_end_clean(); //close and clean the output buffer
ads_fetch_row($r1, 0); // reset the result set pointer to the beginning
if ($number >= 0){
return $number;
} else {
return FALSE;
}
}
It could also be rewritten to count the rows using ads_fetch_row but this was easier for what I needed. With large result sets there could be slower performance using ads_result_all.
You will have to count the rows as they are fetched. (you can see this KB item 070618-1888) or you can execute a second query with the COUNT() scalar (suggest excluding order by if possible)
Here is an example of counting as you go:
$rStmt = ads_do ($rConn, "select id, name from table1");
$RowCount = 0;
while (ads_fetch_row($rStmt))
{
$id = ads_result ($rStmt, "id");
$name = ads_result($rStmt, "name");
echo $id . "\t" . $name . "\n";
$RowCount++;
}
echo "RowCount:" . $RowCount . "\n";
In Version 12 as far as I know you have the function ads_num_rows(). Please see in official documentation for further usage.

Categories