PHP ADODB - Reuse Query Result? - php

How does one reuse a query result with PHP ADODB, at the moment I am doing this, which I assume is inefficient? :
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
$result2 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
while (!$result2->EOF) {
echo $result2->Fields('colname').'<br>';
$result2->MoveNext();
}

To answer my own question, need to use:
$result1->move(0);
so like this:
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
$result1->move(0); // move recordset cursor back to 0
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result2->MoveNext();
}

Related

Printing single result from db2 query in php

I'm running a query on db2 in a php script, which is running successfully but I can't get it to echo the actual ID of the record I've selected. It does echo my success statement showing it ran successfully but I need the actual sessionid for comparison in another query.
Here I'm selecting the record, executing the query and checking for execution, but I'm also trying to use fetch_row and result to return the single selected ID:
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($executeSessionMax)){
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
How can I return the sessionID into a variable properly from db2?
You are passing the wrong parameter to the odbc_fetch_row() as $executeSessionMax is either a True or False depending on successful execution.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($prepareSessionMax )){
// correction here ^^^^^^^^^^^^^^^^^^
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
You could recode as this specially as a MAX() will only ever return one row so the while loop is not needed either.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
if (odbc_execute($prepareSessionMax)) {
odbc_fetch_row($prepareSessionMax );
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
// if echo gets lost try writing to a file
error_log("maxResult = $maxResult", 3, "my-errors.log");
} else {
// something went wrong in the execute
}
You could also try
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$result = odbc_exec($DB2Conn, $latest_result);
$rows = odbc_fetch_object($result);
echo $row->SESSIONID;
$maxResult = $row->SESSIONID;

How to save query in multidimesional array?

I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

PHP Problem with MySQL query. The function is only running for the first mysql result

I tried to search for something similar in the web but no results.
What I am trying to do is simply taking the results from the DATABASE and then run some functions for EACH result.
We have two kinds of functions.
The first function is when the row "Type" is = F , the second one when the row "Type" is = T.
The problem that I am having with this code is that it runs the functions ONLY for the first mySQL result.
But I have more results in the same time, and the functions should run for EACH mySQL result and not only for the first one.
I do not know if I need a foreach or whatever. I do not know anything about arrays and php loops.
Thank you.
include_once("../dbconnection.php");
date_default_timezone_set('UTC');
$TimeZone ="UTC";
$todaydate = date('Y-m-d') ."\n";
$time_utc=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_utc);
$MembID =(int)$_COOKIE['Loggedin'];
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryMAIN="SELECT * FROM TableTuit WHERE TimeZone ='".$TimeZone."' AND Date ='".$todaydate."' ORDER BY ID ASC";
$result=mysql_query($queryMAIN) or die("Errore select TableT: ".mysql_error());
$tot=mysql_num_rows($result);
while($ris=mysql_fetch_array($result)){
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
if($time <= $NowisTime){
if($type=="F") //if the row type is = F, then do the things below
{
$queryF ="SELECT * FROM `TableF` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryF) or die("Errore select f: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
$row = mysql_fetch_assoc($result);
DO FUNCTION // Should call the function that requires the above selected values from $queryF. Should Run this function for every mysql result given by $queryMAIN where row "type" is = F
}
}
}
if($type=="T") //if the row type is = T, then do the things below
{
$queryT = $queryF ="SELECT * FROM `TableT` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryT) or die("Errore select $queryT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count == 0)
$Isvalid = false;
else
{
$Isvalid = true;
$row = mysql_fetch_assoc($result);
}
if($Isvalid){
DO THIS FUNCTION // Should call the function that requires the above selected values from $queryT. Should Run this function for every mysql result given by $queryMAIN where row "type" is = T
}
}
}
}//END OF MYSQL WHILE OF $queryMAIN
You are using $result for the outer Query ($result=mysql_query($queryMAIN); and the Query inside the while loop $result=mysql_query($queryF); - I believe you do not want to mix these?
Right now you process the first row from TableTuit, then overwrite the $result with a row from TableF or TableT. In the next loop, the following columns will not be found in the array (unless they are also in these two tables, of course):
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
You are loading the results into an array, try using this in your while loop instead:
while($ris=mysql_fetch_assoc($result)){

How to use javascript to prompt based on room availability?

I'm new to programming and I need help on my code. I want my page to prompt me if there will be available rooms left. I'm using the onload function on the admin page.
so far here is my code
function prompt()
{
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
?>
if(< ?php $result <= 14 ?>){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
edit:
The code worked fine now but it displays "Resource id#4", not the value of the count.
I feel you can't mix php with js codes.
php is mainly on server side , while the js is client side
from the snippet you provide, maybe you should use purely php as follows:
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
if ($result <= 14) {
echo("Rooms left: $result");
}
else {
echo("Welcome Admin.")
}
?>
This should be run at the first when request
I think you are confused about where PHP processes vs. where Javascript processes.
PHP is processed on the server side, while Javascript is processed on the client side. Think of it like this...
You access a page.
Your PHP is processed, and the final output is sent to the browser.
Your Javascript is processed by the browser.
As you have it now, you'd be getting some funny output... especially because of your lack of echo statements. Here is what you'd probably be seeing in your browser page source:
function prompt()
{
if(){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
Notice the empty if statement (also the space in the start tags:
if(<?php echo ($result <= 14); ?>){
alert("Rooms left: <?php echo $result ?>");
}
This should make your Javascript evaluate a boolean true/false. Don't forget that Javascript needs to be wrapped in a < script > tag too!
To answer your MySQL question...
Try it like this:
//We can alias the COUNT(*) as MyCount for easy reference
$sql = "SELECT COUNT(*) as MyCount FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
$row = mysql_fetch_array($result); //$row is now an array and will now have your count in it
echo $row['MyCount']; //This will print the count from the database. You could use it in other ways as well.
mysql_query returns resource, not a result.
Try to use:
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$count = mysql_result($res, 0, 0);
There should be no space in php tags:
< ?php
^
Should be:
<?php
You are also missing a fetching function, here is how you can get row count in a variable:
<?php $count = mysql_num_rows($result);?>
Later you can use the $count variable in the if condition.
use mysql_fetch_row , and after that in the condition , compare to $row[0]
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$row = mysql_fetch_row($res);
if(< ?php $row[0] <= 14 ?>){

Categories