Add result of multiple sql queries - php

I am trying to add the result of 3 SQL queries. All 3 queries return integer values.
How can I add the results from the 3 SQL queries into a variable and echo it?
The code:
<?php
define('HOST','mywebsite.com');
define('USER','username');
define('PASS','password');
define('DB','imagebase');
$con=mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='POST'){
$val1=$_POST['sval1'];
$val2=$_POST['sval2'];
$val3=$_POST['sval3'];
$sql="select price from images where name='$val1'"; //returns 100
$sql1="select price from images where name='$val2'"; //returns 100
$sql2="select price from images where name='$val3'"; //returns 100
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
$result1=mysqli_query($con,$sql1);
$count1=mysqli_num_rows($result1);
$result2=mysqli_query($con,$sql2);
$count2=mysqli_num_rows($result2);
if ($count==1) {
$res1=$count;
}
if ($count1==1) {
$res2=$count;
}
if ($count2==1) {
$res3=$count;
}
$final=$res1+$res2+$res3; //should return 300 but returns 3
echo $final;
mysqli_close($con);
} else {
echo 'Error Updating Price';
mysqli_close($con);
}
?>

WARNING code in question is VULNERABLE to SQL Injection! Don't do this. Any potentially unsafe values that are included into SQL text must be properly escaped. The preferred pattern is to use prepared statements with bind placeholders.
To address the specific question that was asked: we would need to fetch rows from the resultsets, and accumulate the values returned for price.
It doesn't look like we are concerned with the number of rows that are returned; by each query, so there's not really a reason to call num_rows function.
$tot = 0;
$result=mysqli_query($con,$sql);
while( $row = $result->fetch_assoc() ) {
$tot += $row['price'];
}
$result1=mysqli_query($con,$sql1);
while( $row = $result1->fetch_assoc() ) {
$tot += $row['price'];
}
$result2=mysqli_query($con,$sql2);
while( $row = $result2->fetch_assoc() ) {
$tot += $row['price'];
}
echo "tot = " . $tot;
But why that whole rigmarole of running three separate queries? If what we want is a total, we could have MySQL calculate that for us.
Also, the object oriented pattern is much easier than the procedural pattern.
$sql = 'SELECT SUM(i.price) AS tot_price
FROM images i
WHERE i.name IN ( ? , ? , ? )';
if( $sth = $con->prepare($sql) ) {
$sth->bind_param('sss',$val1,$val2,$val3);
if( $sth->execute() ) {
$sth->bind_result($tot_price);
if( $sth->fetch() ) {
echo "tot_price = " . $tot_price;
} else {
// no row returned
}
$sth->close();
} else {
// handle error in execute
} else {
// handle error in prepare
}

Inside your if statements, you forgot to change $count to $count1 and $count2 in second and third statements.
Also, are you sure you want to check that $count, $count1, $count2 are equal to 1?
You may want to check if those variable have falsy value so if($count) etc.
After that, you need to initialize $res1, $res2, $res3 to 0 before the if statement, otherwise it can occour you get error later when summing $res variables that are not initialized due to falsy if statement before.

Related

Fetching data from two MySQL tables simlutenously with PHP + AJAX

I'm creating a search box that queries two MySQL tables and lists the results in real time. For now though, I have a working prototype that will query only one table. I've written the following PHP code in conjunction with JQuery and it works wonderfully:
HTML
<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>
Javascript
function search(input) {
var inputQuery = input.value;
/* $() creates a JQuery selector object, so we can use its html() method */
var resultsList = $(document.getElementById("search-results-container"));
//Check if string is empty
if (inputQuery.length > 0) {
$.get("search-query.php", {query: inputQuery}).done(function(data) {
//Show results in HTML document
resultsList.html(data);
});
}
else { //String query is empty
resultList.empty();
}
}
and PHP
<?php
include("config.php"); //database link
if(isset($_REQUEST["query"])) {
$sql = "SELECT * FROM students WHERE lastname LIKE ? LIMIT 5";
/* Creates $stmt and checks if mysqli_prepare is true */
if ($stmt = mysqli_prepare($link, $sql)) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_query);
//set parameters
$param_query = $_REQUEST["query"] . '%';
//Try and execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
//get number of rows
$count = mysqli_num_rows($result);
if ($count > 0) {
//Fetch result rows as assoc array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "<h1>Students:</h1>"; //Header indicates student list
for ($i = 0; $i < $count; $i++) {
$name = $row["lastname"];
echo "<p>$name</p>";
}
}
else { //Count == 0
echo "No matches found.<br>";
}
}
else { //Execution of preped statement failed.
echo "Could not execute MySQL query.<br>";
}
} // end mysqli_prepare
} // end $_RESQUEST isset
?>
The details of the students table are arbitrary, except for the fact that it has a String column that lists the student's last name.
My problem is that there is also a staff table which is effectively the same as students but for a different purpose. I'd like to query the staff table at the same time as students, but have the results separated like so:
<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>
<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>
The obvious answer would be to add another $sql statement similar to the one on Line 5 and just do both queries serially - effectively doubling the search time - but I'm concerned this will take too long. Is this a false assumption (that there will be a noticeable time difference), or is there actually a way to do both queries alongside each other? Thanks in advance!
If the two tables have identical structures, or if there is a subset of columns which could be made to be the same, then a UNION query might work here:
SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;
I removed the LIMIT clause because you don't have an ORDER BY clause, which makes using LIMIT fairly meaningless.
Note that I introduced a computed column type which the result set, when ordered by it, would place students before staff. Then, in your PHP code, you would just need a bit of logic to display the header for students and staff:
$count = mysqli_num_rows($result);
$type = -1;
while ($count > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$curr_type = $row["type"];
if ($type == -1) {
echo "<h1>Students:</h1>";
$type = 0;
}
else if ($type == 0 && $curr_type == 1) {
echo "<h1>Staff:</h1>";
$type = 1;
}
$name = $row["lastname"];
echo "<p>$name</p>";
--$count;
}

Why does my PHP PDO Select in while not working with page limit? Also issue with Array in select

Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code? The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates
for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id2 = $row['id'];
$name = $row['name'];
echo 'hello';
}
}
Try to do it like this :
$limit = ($pageno - 1) * $rows_per_page . ',' . $rows_per_page;
for($x = 0; $x <= $v; $x++) {
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc LIMIT " . $limit);
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$id2 = $result['id'];
$name = $result['name'];
echo 'hello';
}
}
You should replace your limit parameter with a PHP variable:
$stmt = $conn->prepare("SELECT * FROM tman
WHERE approve='Y' AND zip=:zipp
ORDER BY id DESC LIMIT $limiter");
According to the PHP PDO::prepare manual in regard to prepared statements:
Use these parameters to bind any user-input, do not include the
user-input directly in the query.
Since preparing a statement lets you filter user input, these parameters, by design are not allowed to replace any other part of the query that is supposed to be set by a developer. For instance allowing a parameter to replace a table name would provide access to an attacker to use the privileges of the user on anything the user has access to. Likewise, in your situation, LIMIT is provided through MySQL as a query optimization. Exploiting this feature can bring down a system where massive datasets exist.
Also you should wrap your PDO query with a Try/Catch statement to prevent others from seeing your PDO exceptions when they're thrown.
//Load your IP here
$dev_ip = 'your.ip.address.here';
//Filter the user's IP
$user_ip = filter_input(INPUT_SERVER,'REMOTE_ADDR', FILTER_VALIDATE_IP);
//Set your limiting variable
$limiter = ($pageno-1)*$rows_per_page.','.$rows_per_page;
for($x = 0; $x <= $v; $x++) {
try {
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve='Y' AND zip=:zipp ORDER BY id desc LIMIT $limiter");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
if(array_key_exists($x, $zipcodeA)&&!empty($zipcodeA[$x])){
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (array_key_exists('id', $result)&&!empty($result['id'])) {
$id2 = $result['id'];
} else {
if($user_ip==$dev_ip){
echo 'No ID';
}
}
if (array_key_exists('name', $result)&&!empty($result['name'])) {
$name = $result['name'];
} else {
if($user_ip==$dev_ip){
echo 'No Name';
}
}
}
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
if($user_ip==$dev_ip){
echo $ex->getMessage();
}
}
}
Don't base your loop condition on the result of fetch(). Get the result and evaluate it separately.
From the docs: "The return value of this function on success depends on the fetch type." IE Not necc a great thing for a boolean evaluation. It will return false if it fails but when it succeeds it may behave in an unexpected manner.
Better - use fetchAll() and loop through the resultant array.
Last - check your result set using print_r(). Make sure you have something to loop through.

How to sum up values in a php column

Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");

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!

How to identify the query that caused the error using mysqli_multi_query?

Using a example from elsewhere on SO to better catch 'hiding' errors. While the code below will catch and return an error, is it possible to improve this to report for which query the error occurred?
With the code below, the output is:
Columns: 18
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FRO inventory' at line 1
Code being tested:
$query = "SELECT * FROM orders WHERE location = 'IN' ORDER BY orderNum DESC LIMIT 20;";
$query .= "SELECT * FRO inventory"; // With error
$ord = array();
$invent = array();
if(mysqli_multi_query($link, $query)) {
do {
// fetch results
if($result = mysqli_store_result($link)) {
echo 'Columns: ' . mysqli_field_count($link) . "<br>";
while($row = mysqli_fetch_assoc($result)) {
if(count($row) > 17)
$orders[] = $row;
elseif(count($row) == 6)
$inv[] = $row;
}
}
if(!mysqli_more_results($link))
break;
if(!mysqli_next_result($link)) {
// report error
echo 'Error: ' . mysqli_error($link);
break;
}
} while(true);
mysqli_free_result($result);
}
Here is an approach that will not only improve the quality of your error messages, it will improve the way you handle your result sets.
$q["Orders"] = "SELECT * FROM orders WHERE location = 'IN' ORDER BY orderNum DESC LIMIT 20";
$q["Inventory"] = "SELECT * FRO inventory";
if (!$link = mysqli_connect("host", "user", "pass", "db")) {
echo "Failed to connect to MySQL: " , mysqli_connect_error();
} elseif (mysqli_multi_query($link, implode(';', $q))) {
do {
$q_key = key($q); // current query's key name (Orders or Inventory)
if ($result = mysqli_store_result($link)) { // if a result set... SELECTs do
while ($row = mysqli_fetch_assoc($result)) { // if one or more rows, iterate all
$rows[$q_key][] = $row;
}
mysqli_free_result($result);
echo "<div><pre>" . var_export($rows[$q_key], true) . "</pre></div>";
}
} while (next($q) && mysqli_more_results($link) && mysqli_next_result($link));
}
if ($mysqli_error = mysqli_error($link)) { // check & declare variable in same step to avoid duplicate func call
echo "<div style=\"color:red;\">Query Key = " , key($q) , ", Query = " , current($q) , ", Syntax Error = $mysqli_error</div>";
}
Error on first query:
If your first query tries to access a table that doesn't exist in the nominated database like: ordersXYZ
Array $rows will not exist, no var_export() will occur, and you will see this response:
Query Key = Orders, Query = SELECT * FROM ordersXYZ WHERE location='IN' ORDER BY orderNum DESC LIMIT 20, Syntax Error = Table '[someDB].ordersXYZ' doesn't exist
Error on second query:
If your first query is successful, but your second query tries to access a non-existent table like: inventory2
$rows["Orders"] will hold the desired row data and will be var_export()'ed, $row["Inventory"] will not exist, and you will see this response:
Query Key = Inventory, Query = SELECT * FROM inventory2, Syntax Error = Table '[someDB].inventory2' doesn't exist
No errors:
If both queries are error free, your $rows array will be filled with the desired data and var_export()'ed, and there will be no error response. With the queried data saved in $rows, you can access what you want from $rows["Orders"] and $rows["Inventory"].
Things to note:
You may notice that I am making variable declarations and conditional checks at the same time, this makes the code more concise but some devs prefer to avoid this.
As my approach uses implode() with a semi-colon on the elseif line, be sure not to add a trailing semi-colon to your queries.
This set of queries always returns a result set because all are SELECT queries, if you have a mixed collection of queries that affect_rows, you may find some useful information at this link(https://stackoverflow.com/a/22469722/2943403).
mysqli_multi_query() will stop running queries as soon as there is an error. If you are expecting to catch "all" errors, you will discover that there will never be more than one.
Writing conditional break points like in the OP's question and solution is not advisable. While custom break points may be rightly used in other circumstances, for this case the break points should be positioned inside of the while() statement of the do() block.
A query that returns zero rows will not cause a error message -- it just won't create any subarrays in $rows because the while() loop will not be entered.
By using the key() function, the OP's if/elseif condition that counts the columns in each resultset row can be avoided. This is better practice because running a condition on every iteration can become expensive in some cases. Notice that the array pointer is advanced inside of $q at the end of each do() iteration. This is an additional technique that you will not find on the php manual page; it allows key() to work as intended.
And, of course, the <div><pre>var_export()...</pre></div> line can be removed from your working code -- it was purely for demonstration.
If you are going to run any more queries after this code block that reuse variables, be sure to clear all used variables so that residual data does not interfere. e.g. $mysqli_error=null; // clear errors & reset($q); // reset array pointer.
Take heed to this somewhat vague warning at your own discretion: http://php.net/manual/en/mysqli.use-result.php :
One should not use mysqli_use_result() if a lot of processing on the
client side is performed, since this will tie up the server and
prevent other threads from updating any tables from which the data is
being fetched.
Lastly and MOST IMPORTANTLY for security reasons, do not display query or query error information publicly -- you don't want sinister people to see this kind of feedback. Equally important, always protect your queries from injection hacks. If your queries include user-provided data, you need to filter/sanitize the data to death before using it in mysqli_multi_query(). In fact when dealing with user input, my very strong recommendation is to move away from mysqli_multi_query() and use either mysqli or pdo prepared statements for your database interactions for a higher level of security.
To answer my own question and since the documentation is poor, here's a solution that hopefully will help others. What was missing is a way to catch an error on the 1st query. (The hidden actions of myqsqli_multi_query are difficult to understand.)
Now check for entries in $err array.
$q[1] = "SELECT * FROM orders WHERE location = 'IN' ORDER BY orderNum DESC LIMIT 20";
$q[2] = "SELECT * FROM inventory";
$ord = array();
$invent = array();
$err = array();
$c = 1;
if(mysqli_multi_query($link, implode(';', $q))) {
do {
// fetch results
if($result = mysqli_use_result($link))
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
if(count($row) > 17)
$orders[] = $row;
elseif(count($row) == 6)
$inv[] = $row;
}
}
$c++;
if(!mysqli_more_results($link))
break;
if(!mysqli_next_result($link) || mysqli_errno($link)) {
// report error
$err[$c] = mysqli_error($link);
break;
}
} while(true);
mysqli_free_result($result);
}
else
$err[$c] = mysqli_error($link);
mysqli_close($link);
In your do loop, add a counter, each successful mysqli_next_result increment the counter. Once mysqli_next_result returns false, output the counter as well.
This works for two queries.
If the error is in the first, the response for 1st query to PHP is the error message, and for the second (which won't fire), a message tattling on the first.
If the error is in the second, the first's response is returned and the 2nd gets the error message.
I'm using associative arrays and nixing array elements[0].
This adds ['Error'] key only if there is a relevant error.
Finally, I'm not the best PHPer, so it's up to you to fix what's ugly.
$query_nbr=0;
if (mysqli_multi_query($link,$query ))
{
do
{
unset($field_info) ; $field_info = array() ;
unset($field_names) ; $field_names = array() ;
unset($values) ; $values = array(array()) ;
if ($result = mysqli_store_result($link))
{
$query_nbr += 1 ;
$rows_found = mysqli_num_rows($result);
$fields_returned = mysqli_num_fields($result);
$field_info = mysqli_fetch_fields($result);
$field_nbr=0;
foreach ($field_info as $fieldstuff)
{ $field_nbr +=1 ;
$field_names[$field_nbr] = $fieldstuff->name ;
}
$now = date("D M j G:i:s T Y") ;
if ($query_nbr == 1)
{
$result_vector1 = array('when'=>$now) ;
$result_vector1['nrows']=0;
$result_vector1['nrows']=$rows_found ;
$result_vector1['nfields']=$fields_returned ;
$result_vector1['field_names']=$field_names ;
}
else
{
$result_vector2 = array('when2'=>$now) ;
$result_vector2['nrows2']=0;
$result_vector2['nrows2']=$rows_found ;
$result_vector2['nfields2']=$fields_returned ;
$result_vector2['field_names2']=$field_names ;
}
$row_nbr=0 ;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
$row_nbr++ ;
for ($field_nbr=1;$field_nbr<=$fields_returned;$field_nbr++)
{
$values[$row_nbr][$field_names[$field_nbr]] =$row[$field_nbr-1] ;
}
}
mysqli_free_result($result) ;
unset($values[0]) ;
if ($query_nbr == 1)
{$result_vector1['values']=$values ;}
else
{$result_vector2['values2']=$values ;}
} // EO if ($result = mysqli_store_result($link))
} while (mysqli_more_results($link) && mysqli_next_result($link)) ;
} // EO if (mysqli_multi_query($link,$query ))
else
{
// This will be true if the 1st query failed
if ($query_nbr == 0)
{
$result_vector1['Error'] = "MySQL Error #: ".mysqli_errno($link).": ".mysqli_error($link) ;
$result_vector2['Error'] = "MySQL Error in first query." ;
}
} // EO MySQL
// Here we only made it through once, on the 2nd query
if ( $query_nbr == 1 && $nqueries == 2 && empty( $result_vector2 ) )
{
$result_vector2['Error'] = "MySQL Error #: ".mysqli_errno($link).": ".mysqli_error($link) ;
}

Categories