Out of memory, Mysql_query() unable to save resultset - php

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.

Related

php running mysql_query in a for loop

I have different paramter of particular mysql query I am running so I need to run them in bunch.. so say
$server = 'server_';
for ($a=0 ; $a<5 ; ++$a) {
$criteria = $server . $a;
$query1 = 'select blabh blah not important ' . $criteria . 'order by date desc limit 10';
$query_result = mysql_query($query1);
}
Above only comes back results for server_4
I naively thought I could just do
$query_result .= mysql_query($query1);
But clearly that doesn't work. I hope no one says why don't you run mysql as
like '$server%'
I am looking for to see if what I am trying to do is possible. appending.. I guess string append is possible but I perahps simply don't understand what's coming back from mysql?
fetch code sample
select * from tableName where server like $criteria order by date desc limit 10
=========================================================
code sample
$data = array();
$dataMaster = array();
for ( $x = 0; $x <= 8; $x++ ) {
$server = ‘server_’ . $x;
$myquery = 'select * from serverTable where servername like ' . '"' . $server . '"' . ' order by date1 desc limit 100';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ( $x = 0; $x < mysql_num_rows($query); $x++ ) {
$data[] = mysql_fetch_assoc($query);
}
$data = array_reverse($data);
array_push($dataMaster, $data);
}
echo json_encode($dataMaster)
Try to avoid SQL inside PHP loop, you can do the following instead:
SELECT * FROM serverTable WHERE servername IN
('server_0', 'server_1', 'server_2', 'server_3', 'server_4')

How can i execute a program if the monster id doesnt exist?

This is my current code.
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE MonsterId = '$monster_id'") or die(mysql_error());
$char_result = mysql_query("SELECT * FROM xx_characters WHERE id = '" . $char_id . "'") or die(mysql_error());
$char = mysql_fetch_assoc($char_result);
if (mysql_num_rows($monster_result) > 0) {
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE MonsterId = " . $monster_id) or die(mysql_error());
//I tried adding this, but for some reason it messed up the entire thing
//exec("/usr/local/bin/lostID $monster_id");
} else {
$level = $char['level'] + 1;
$level2 = $char['level'] - 10;
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE Level < " . $level . " AND Level > " . $level2 . " AND ExtraData != 'trainer' AND ExtraData != 'starter' ORDER BY RAND() LIMIT 1") or die(mysql_error());
}
$monster = mysql_fetch_assoc($monster_result);
I tried to add it under else too, but it renders the page totally blank, there are echo statements after this. Whats wrong?
Try the function isset($variable_name)
I would suggest to use
if(!empty($monster_id)) {
// your code here
}
Empty function will also make sure that variable value should not be null or empty string.

Score board php loop

I am fairly new to php so probably my question will sound simple for many, but here is my issue.
I have a table in MySQL holding scoreboard for users.
$connection = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table() {
global $sql;
if ($sql) {
$rows_num = mysql_num_rows($sql);
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i <= $rows_num; $i++) {
echo $i;
}
echo $i.$row['name']." ".$row['score']."<br />\n";
}
}
}
the result im getting is :
123456Player1 3
123456Player2 400
123456Player3 784
123456Player4 1500
123456Player5 1642
So there is 5 players. Although firstly $i has 6 results and it is going through the entire loop for each player.
What i am trying to achieve is this:
1Player1 3
2Player2 400
3Player3 784
4Player4 1500
5Player5 1642
where first number is simply position. So whoever has less points is on the first place.
$connection = mysql_connect('localhost' ,'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table()
{
global $sql;
$i=1;
if($sql)
{
while($row = mysql_fetch_array($sql))
{
echo $i++ . $row['name'] . " " . $row['score'] . "<br />".PHP_EOL;
}
}
}

mysql search using for loop from php

i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.

Retrieving values from MySQL

I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...

Categories