will mysql_fetch_array fail if connection lost during the fetch? - php

I want to loop multiple times through my query results, and I have 2 ways in mind:
1-
while($data = mysql_fetch_array($res , MYSQL_ASSOC)
{
array_push($new_arr , $data);
}
foreach($sites as $s){
foreach($new_arr as $d)
{
//some code
}
}
2-
foreach($sites as $s){
while($data = mysql_fetch_array($res , MYSQL_ASSOC)
{
//some code
}
mysql_data_seek($res,0);//set the pointer
}
My question: I think option 2 is more efficient but what if I lose connection to db during the mysql_fetch_array(option 2)? I get allot of results; this will take around 10-20 minutes. Will that affect the query results($res) or are they safe?

The data is mapped into a buffer assigned by the mysql client when you execute mysql_query() therefore losing the connection is irrelevant. The first method you cite will create a further copy of the data as a PHP array - which is not very efficient.
Also, WTF is the nested loop ($sites) doing? It looks like either your data is not mormalized or you've got a very bad algorithm.

Related

Execute multiple queries in a single database connection using oracle 10g and php

I want to run multiple sql queries in a single database connection using oracle 10g and php. Here for every sql query queries I have to create database connection. Is there any way to run multiple sql queries in a single database connection or we have to fetch data this way only? Because when we have to run 50 queries, we have to write 50 times like below.
<?php
include("mydb.php");
// run query
$sql6 = "select * from dat where to_char(WD,'dd/mm')='19/08'";
$stid6=oci_parse($conn, $sql6);
// set array
$arr6 = array();
if(!$stid6){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r6=oci_execute($stid6);
if(!$r6){
$e=oci_error($stid6);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid6,OCI_ASSOC)){
// add each row returned into an array
$arr6[] = array(($row['WD']) , (float)$row['DATA']);
}
oci_free_statement($stid6);
oci_close($conn);
?>
<?php
include("mydb.php");
// run query
$sql7 = "select * from dat where to_char(WD,'dd/mm')='11/03'";
$stid7 = oci_parse($conn, $sql7);
// set array
$arr7 = array();
if(!$stid7){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r7=oci_execute($stid7);
if(!$r7){
$e=oci_error($stid7);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid7,OCI_ASSOC)){
// add each row returned into an array
$arr7[] = array(($row['WD'])) , (float)$row['DATA']);
}
oci_free_statement($stid7);
oci_close($conn);
?>
................
................
*Pardon me, I forgot to mention that we have store day-wise data in different array. I mean to say that 11/03's data will store in arr1 and 19/08's data will be stored in arr2. Not in same array.
(this should be a comment, but its a bit long)
I don't want to be disparaging here, but your question is alarming naive - so much so that it should be closed as off-topic.
Your code exhibits a lack of understanding about modular programming and variable scope. These should be covered by day 2 of a programming-from-scratch course. but oddly includes some more sophisticated PHP specific programming, but apalling SQL - it looks like someone else wrote the code as a quick hack and now you are trying to extend its capabilities.
That you are using an Oracle database, raises all sorts of questions about why are attempting this (Oracle is expensive; how can someone afford that but not afford to provision you with the skills you need?)
The solution to the problem as you have described it is to re-implement the script as a function that takes the OCI connection and SQL statement as parameters, then simply....
<?php
include("mydb.php");
$queries=array(
"select * from dat where to_char(WD,'dd/mm')='11/03'",
"select * from dat where to_char(WD,'dd/mm')='19/08'"
);
foreach ($queries as $sql) {
run_qry($sql, $conn);
}
oci_close($conn);
exit;
function run_query($sql, $conn)
{
$stid=oci_parse($conn, $sql);
// set array
$arr = array();
if(!$stid){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
...
oci_free_statement($stid);
return $arr;
}
However since the 2 example queries have exactly the same structure, there are other ways to the results of what are multiple queries - merging the SQL states into a single select using OR or UNION, using parameterized queries. Since the code you've shown us simply throws away the results its hard to say how you should approach the task.

php odbc result unsetting

So, here's my issue: I have a function that queries sql and pulls it into a resource. In this function, I run:
if (odbc_num_rows($rs) === 0) {
return FALSE;
} else {
if ($type !== "Issues") {
while (odbc_fetch_row($rs)) {
$issues['tvi'][] = odbc_result($rs, 'TitleVolumeIssue_c_');
}
}
return $rs;
}
This does exactly what it is supposed to do. However, when I pass $rs into the next method for parsing into html, it seems as though $rs gets unset. Oddly, I can call odbc_num_rows($rs) and it gives me the correct number of rows, but dumping the var shows it is false and I can't loop through the resource to get any values.
How can I either free up that resource so that it can be used in the next function or how can I rewrite the IF condition so that I get the values without unsetting the resource?
Each time you fetch it moves the database cursor to the next row.
So odbc_fetch_row() keeps going to the next row, until the last one. After that it returns false.
Unfortunately you cannot move the row pointer back to the first record.
You will have to query your DB one more time.
Another option for this would be to store the odbc result in an array that you can loop through using a foreach. This preserves the data and you only have to query once vs multiple times (helps when dealing with a lot of data).
while($row = odbc_fetch_array($rs)) {
$resultsArray[] = $row;
}
Then loop through it like this...
foreach ($resultsArray as $key=>$value){
//Do what you need to do...
}
I had a similar problem in my question here and #Jeff Puckett was able to explain it pretty well.

returning results from a column into an array

I am very new to PHP and I realise I have a lot to learn, especially about SQL injection attacks and the new php 5.5 oo stuff.
However, whilst I am learning I try to play about a bit and experiment and I have come across a problem. I need to get all results from one column (team_name) of my query into an array (zero indexed would be easier) so that I can put those results into a foreach loop to create a fixture list. For example - this is what I would like to do with the data...
foreach ($teams as $team) {
foreach ($teams as $opposition) {
if ($team != $opposition) {
echo "$team versus $opposition";
}
}
}
So my sql query is as follows...
$query="select * from pool_a";
$result=mysql_query($query);
$num=mysql_num_rows($result);
Then I can easily output the data I am looking for as follows;
echo "<table>";
for ($i=0;$i<$num;$i++) {
$teams=mysql_result($result,$i,'team_name');
echo "<tr><td>$teams</tr>";
}
echo "</table>";
But what I can't do is get the data into an array. I thought that data that came back from a msql_query such as the above always came back as an array, no matter the number of results, but if I run an is_array() check on $teams, it returns false.
I have tried using explode (after adding a comma after each team name and trimming the last one off) and then using a foreach loop but it only ever returns the value associated with the index [0]. I should add here that although the key is 0, the actual value I get is the LAST in the list when echoed as above, which I also don't understand.
Any help would be much appreciated.
Thanks
$team_names = array();
while ($row = mysql_fetch_assoc($result)) {
$team_names[] = $row['team_name'];
}
mysql_fetch_assoc, mysql_fetch_row, and mysql_fetch_array all return a row as an array (they differ in how it's indexed). But mysql_result just returns a single item from the result, so it doesn't return an array.
You could do the same thing as above with your use of mysql_result, but you still have to push them onto the result array yourself:
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[] = $team;
}
To get the results of the query into an array, you can do this
$query="select * from pool_a";
$result=mysql_query($query);
$result_arr = mysql_fetch_array($result);
$num=mysql_num_rows($result);
However, consider using the PDO drivers to connect to the database. It's far superior to doing it procedurally, and it's safer as Prepared Statments will help protect you against injection attacks. The method you're using is deprecated.
Instead of using mysql_result try using mysql_fetch_array($result, MYSQL_ASSOC)
This function will give you an array of whatever your result from MySQL is.

Running while($row = sqlsrv_fetch_array($result)) multiple times

I am retrieving a couple of tables from a MSSQL database, which I am then running through to obtain order information from.
My code looks like this:
while($row = sqlsrv_fetch_array($orderResult))
{
......code........
..................
while($statusRow = sqlsrv_fetch_array($statusResult))
{
....code....
}
....code....
}
Now my problem is that after the second loop runs through, it never runs again. And I need it to run every time the first loop runs.
Is there anything I can do to reset that second loop to run again?
Thank you in advance. Any help or a push in the right direction will be very helpful.
Read about the other parameters in sqlsrv_fetch_array()
You can do something like this to reset
// reset, and get first row
$row = sqlsrv_fetch_row($result, SQLSRV_FETCH_BOTH, SQLSRV_SCROLL_FIRST);
// get second (and nth row) normally
$row = sqlsrv_fetch_row($result);
Alternatively, I think you could benefit from doing a JOIN in your query to return a single result. Merging results manually like this seems a little hackish.
I had a similar problem when calling a stored proc from a database that returned multiple result sets. I found Macek's answer didn't work for me, but another answer did:
$resultSet = array();
$isNotLastResult = true;
$i = 0;
while (!is_null($isNotLastResult))
{
$resultSet[$i] = array();
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$resultSet[$i][] = $row;
}
$isNotLastResult = sqlsrv_next_result($result);
$i++;
}
print_r($resultSet);
PS: I gave you an up arrow to counteract your down arrow. You asked a question I spent quite a bit of time looking for the answer to. Good question!
Use the following to reset the pointer:
sqlsrv_fetch_array ($Res, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1);
Then use the same code as before to loop through the result set. sql_fetch_array appears to increment the pointer after retrieving the data. Requesting the -1 record retrieves nothing but then sets the pointer to 0 which is the first record.
are you sure your second loop got results for a second run ? maybe, if your $statusResult depents on your $row and your $row has just entries for the first loop you should insert some pseudo-entries to your db.
the second loop should refresh itself in the next "big" loop cause the whole inner block will be destroyed at the end of the big block and will be (fully) rebuild at the next entry.

How would I do this in php?

I'm implementing a memcache to cache mysql query results.
It loops through the mysql results using
while($rowP3= mysql_fetch_array($result3)) {
or it loops through the memcached results (if they are saved in memcache, and not expired) via
foreach($cch_active_users_final as $rowP3) {
How can I get it to show the right looping method based on if the memcached value exists or not. I just want it to pick the right looping method. I could just duplicate the entire while { } function with all its contents, but I don't want to repeat that huge chunk of code, just so I can change while to foreach
The logic should be something like:
(partial pseudocode)
$data = get_memcached_data('cch_active_users_final');
if (!$data) {
$query = mysql_query(..);
$data = array();
while($row = mysql_fetch_array()) {
$data[] = $row;
}
store_in_memcache('cch_active_users_final', $data);
}
// do whatever you want with $data
If I understand your question, this code doesn't make sense. After querying database comparing queried results to cached values doesn't make sense.
If the $row and $rowP3 values contain the same data, you could have whatever happends in the loops in a function, and pass the row as an argument.
You don't, you use a unified method using PDO.

Categories