I am trying to solve a problem where I need to execute a query on the database within a do while loop and keep on adding to the resultset. However once its finished running all the queries and I then start processing the result set php gives the error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
string given in
The idea is it executes a query with a limit of 0,2 then executes again with a limit of 2,2 and so on until the numbers of rows returned is empty. I know the best solution would be to do a count and work out from there but this is not an option as the database is too large.
Below is the code that I currently have
$tempResult = "";
$i = 0;
$result = null;
do
{
if (is_resource($tempResult))
{
echo 'Cleared Result <br />';
mysql_free_result($tempResult);
}
echo 'Count: ' . $i . '<br />';
$query = "select * from table_test LIMIT $i, 2";
$tempResult = mysql_query($query) or die ("MySQL Error: " . mysql_error());
echo 'Temp Result: ' . $tempResult .' <br />';
$i = $i + 2;
$result .= $tempResult;
} while (mysql_num_rows($tempResult) > 0);
while ($myrow = mysql_fetch_array($result))
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] .
' + ' . $myrow['col3'] . ' <br />';
}
Thanks for any help you can provide.
Why dont you use a result array? For example something like this:
$tempResult = "";
$i = 0;
$resultArray = array();
$result = null;
do
{
if (is_resource($tempResult))
{
echo 'Cleared Result <br />';
mysql_free_result($tempResult);
}
echo 'Count: ' . $i . '<br />';
$query = "select * from table_test LIMIT $i, 2";
$tempResult = mysql_query($query) or die ("MySQL Error: " . mysql_error());
$resultArray = merge($resultArray, mysql_fetch_array($tempResult));
echo 'Temp Result: ' . $tempResult .' <br />';
$i = $i + 2;
} while (mysql_num_rows($tempResult) > 0);
while ($resultArray as $myRow)
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] .
' + ' . $myrow['col3'] . ' <br />';
}
Well, from such an unusual question we can only guess the right answer.
My bet:
Your goal is to do some calculations on the data stored in the table.
And you are going to do it in the PHP script instead of the proper way of calculating using database facilities.
So, it's better you would do all the calculations in one query.
Anyway,
It is always a good practice to ask a core question, a root problem, instead of a question related to some unusual way you choose to solve it.
Once you ask this one, you will get complete and professional answer.
Why not just print the results in the first loop?
$i = 0;
do
{
$query = "SELECT * FROM table_test LIMIT $i, 2";
$result = mysql_query($query) or die("MySQL Error: " . mysql_error());
while ($myrow = mysql_fetch_array($result))
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] . ' + ' . $myrow['col3'] . ' <br />';
}
$i = $i + mysql_affected_rows();
} while (mysql_affected_rows() > 1);
echo 'Count: ' . $i . '<br />';
But really, this method just seems like a way to add additional overhead to fetching rows from the database.
Related
I am currently trying to output the value of an array using a for loop.
I have tried outputting the query that is running in the loop (Resulting in an echo of 24 queries)
1
$number_of_beams = 24;
for ($i = 0; $i < $number_of_beams; $i++)
{
$query = "SELECT fitacf_data.time,
SUM(fitacf_data.num_pts) AS point_total
FROM
fitacf_data
WHERE abbrev = '" . $radar_array[0]['radar_abbrev'] ."'
AND fitacf_data.beam = '" . $i . "'
GROUP BY fitacf_data.time";
$result = pg_query($query) or die('Error: ' . pg_last_error());
while ($row = pg_fetch_array($result)) {
$beam_total_array[] = $row;
}
echo $i
echo $beam_total_array[0]['point_total'] . "<br><br>";
}
If I hard code $i to any value from 0-23 echo $beam_total_array[0]['point_total']; outputs the correct value 24 times.
ie:
2
for ($i = 0; $i < $number_of_beams; $i++)
{
$query = "SELECT fitacf_data.time,
SUM(fitacf_data.num_pts) AS point_total
FROM
fitacf_data
WHERE abbrev = '" . $radar_array[0]['radar_abbrev'] ."'
AND fitacf_data.beam = '5'
GROUP BY fitacf_data.time";
$result = pg_query($query) or die('Error: ' . pg_last_error());
while ($row = pg_fetch_array($result)) {
$beam_total_array[] = $row;
}
echo $i
echo $beam_total_array[0]['point_total'] . "<br><br>";
}
$i is returning 0-23 as expected.
If I run the code as shown in #1 using the $i variable the output is 0 for the 24 times.
What am I missing here?
The problem is that you're declaring $i as a string, which has a value of 0. Remove the double quotes around $i: AND fitacf_data.beam = ' . $i . '
This is cancel_order function,that also in it will call the increase_gameamount() function, i am trying to call increament_gameamount() function it works but when I try to call it from while loop nothing changes in database.
//cancel function
function cancel_order($ord) {
global $conn;
$bqty = 0;
$gqty = 0;
$res = array();
echo "entered cancel function " . $ord . "<br>";
$st = "select (B_qty+G_qty) newqt, B_GM_ID from tb_basket b, tb_game g
where b.B_GM_ID = g.G_ID
and B_O_ID='$ord' ";
$sql = $conn->prepare($st);
$sql->execute();
$sql->bind_result($newqt, $gid);
$i = 0;
while($row = $sql->fetch()) {
$res[$i][0] = $newqt;
$res[$i][1] = $gid;
$i++;
}
$j = 0;
$sql->free_result();
$sql->close();
while($j < sizeof($res)) {
echo $gd = $res[$j][0] . "<br>";
echo $qty = $res[$j][1] . "<br>";
increament_gameamount($gd, $qty);
$j++;
}
}
//increament function
function increament_gameamount($gameid, $new_qty) {
global $conn;
echo "entered increament_gameamount function";
echo $gameid;
echo $new_qty;
$varupdateqty = $conn->prepare("update tb_game set G_qty=? where G_ID=?");
$varupdateqty->bind_param("ss", $new_qty, $gameid);
$varupdateqty->execute();
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
As I stated in the comments I think you are failing on the WHERE of your query because
echo $gd=$res[$j][0]."<br>";
is making $gd a string like 125<br> and the DB cannot find that.
Also, this would cause an error but if the type of your column is int and you pass:
echo $qty=$res[$j][1]."<br>";
again you make $qty something like 1000<br> and that would fail again this would be an error the above for ID check would not.
UPDATE
Just realized I did not specifially state the resolution. Set the variables then echo them and you should be all good.
$gd=$res[$j][0];
$qty=$res[$j][1];
echo $gd . "<br>" . $qty . "<br>";
I am trying to pull all the column names from my database 'settings' and list them in PHP.
A bit of research has come up with the following:
SHOW COLUMNS FROM settings
but I don't know how to go about listing these off through PHP.
it would be helpful if any code posted was a prepared statement format, but not required.
Here is my PHP, it's giving me this error:
Notice: Undefined index: sThumbWidth in /home/demomycm/public_html/subdomains/mercury/eshop/library/classes/class.settings.php on line 204
for every field in my database.
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
$loadColumns[$row['Field']];
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}
use describe
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
In your code you have $loadColumns as an array.
This line does nothing: $loadColumns[$row['Field']];
Basically your getting the value in $loadColumns with the key associated with $row['Field'] and not assigning anything.
You want something like this perhaps for that line:
array_push($loadColumns,$row['Field']);
Full code below
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
array_push($loadColumns,$row['Field']); //<-- this line has been changed
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}
On MySQL connection (deprecated) you can use:
mysql_list_fields
On PDO (recommend) use:
$query = $dbh->prepare("DESCRIBE tablename");
$query->execute();
$tableFields = $query->fetchAll(PDO::FETCH_COLUMN);
On PDO you can also use PDOStatement::getColumnMeta(). But it has the status: EXPERIMENTAL
I have the following code snippet that builds chained select boxes based on data pulled from MySQL.
The first select uses a DISTINCT on a column called PartTypeDescription. This code works awesome if the values in the column are numerical in nature (example: 11). You choose the first select and then the second select is populated as it should.
The problem occurs when the data is text (example: Plumbing). You choose Plumbing for example and the second select box is empty. I'm assuming the second query that builds the second select box is not working correctly. Is there something in the code below that does not allow text values?
/* Configure the select boxes */
if (isset($_GET['key'])) {
$key = $_GET['key'];
switch ($key) {
case 'callTypeSelect':
$select = new SelectBox('What vehicle are you working from?','Choose a vehicle');
$res = mysql_query('SELECT DISTINCT PartTypeDescription FROM ' . DB_TABLE2);
$callTypes = array();
for ($i = 0; list($callType) = mysql_fetch_row($res); $i++) {
$callTypes[] = $callType;
$select->addItem($callType, 'brandSelect-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
break;
default:
if (strpos($key, 'brandSelect-') === 0) {
$callType = str_replace('brandSelect-', '', $key);
$resBrands = mysql_query('SELECT Invm_InventoryNumber FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = ' . mysql_real_escape_string($callType) . " ORDER BY Invm_InventoryNumber");
$select = new SelectBox('What part number are you looking for?', 'Pick a part');
for ($i = 0; list($brand) = mysql_fetch_row($resBrands); $i++) {
$select->addItem($brand, 'result-' . $brand . '-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
} elseif (strpos($key, 'result-') === 0) {
list($null, $brand, $callType) = explode('-', $key);
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
$markup = '';
for ($i = 0; $row = mysql_fetch_assoc($res); $i++) {
//$row = array_map('htmlspecialchars', $row); it looks like the items is already encoded
$markup .= <<<HTML
You can't escape characters inside of single quotes. For example:
$x = 'I don\'t like tomatoes';
That won't escape the quote like you think it would and will cause problems. In your code with this line:
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
You need to wrap strings with escape sequences with double quotes.
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. " WHERE PartTypeDescription = \'" . mysql_real_escape_string($callType) . "\'
AND Invm_InventoryNumber = \'" . mysql_real_escape_string($brand) . "'");
I try to load about 30.000 record to mysql select. than i get this warning.
and than i try to break them into smaller limit. Every 1000. but why i still get this warning?
this is my code :
function processDataDb()
{
$rowIncrement = 1000;
$query = "SELECT count( * ) as totalfield FROM `isc_xml_data` ";
$result = mysql_query($query) or die ("$query" . mysql_error());
if ($result)
{
$row = mysql_fetch_assoc($result);
$total_row = $row['totalfield'];
for($i = 0; $i < $total_row ; $i+=$rowIncrement)
{
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " . $i . " , " . ($i + $rowIncrement - 1);
$res_c = mysql_query($sql_c) or die (mysql_error());
while($row = mysql_fetch_object($res_c))
{
echo $row->id."\n";
$this->insertAndUpdateProduct($row->xmldata);
}
unset($res_c);
}
} else {
echo "result is unavailable";
}
}
Thanks for any help.
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " .
$i . " , " . ($i + $rowIncrement - 1);
http://dev.mysql.com/doc/refman/5.0/en/select.html#id714605
The second argument to LIMIT is how many you want, not the upper bound; try just $rowIncrement.
unset($res_c); It's not valid, there is mysql_free_result($res_c) function for this.
Also, you can do it without first query with count(*) - just make your cycle queries until at least one row returned.
Because of this line:
$this->insertAndUpdateProduct($row->xmldata);
it's your XML processing being very inefficient memory-wise,
while mysql consumes no more than only one row contents.