multiple mysql query result in single array - php

how can i add result of multiple queries in a single array so it makes it easier to later output.
for example,
$newArray = array("mike", "john");
while ($newArray !== false){
$sql = "Select * from accounts where name = '$newArray'";
$result = mysqli_query($db_connection,$sql);
}
while ($row = mysqli_fetch_assoc($result)) {
printf $row['firstName'];
echo "----";
printf $row['num_accounts'];
echo "----";
prinf $row['location'];
echo "----";
echo "<br>";
}
i am sure i am missing something that obvious. but the idea is that i want to setup a loop to read from an array and then execute the query and store the results. each time query executes the condition is different but from same table, , but then keep adding the results to single output, making it easier to output in the end.

you could avoid the while simple using in clause based on list of values you need
$newList = "'mike', 'john'";
$sql = "Select * from accounts where name IN (" .$newList .")";
but you should not use php var in sql ..you are at risk for sqlinjection .. for avoid this you should take a look at your sqldruver for binding param ..
but if you want append the result for different where condition on same table you should take a look at UNION clause
$sql = "Select * from accounts where name IN (" .$newList .")
UNION
Select * from accounts where you_col > 10";

There's a few things wrong with your code..
1. You are inputting a full array into your query.
2. You're doing no preparations on your query thus it's vulnerable to sql injection if $newArray is human input data.
3. Your logic from looping thru the data, if you managed to get a single query correct, would always loop thru the last query. You need to move the $row = mysqli_fetch_assoc($result) stuff inside your actual loop.
To get this code working it would look like so:
$newArray = array("mike", "john");
foreach($newArray as $name){
$sql = "Select * from accounts where name = '{$name}'";
$result = mysqli_query($db_connection,$sql);
while ($row = mysqli_fetch_assoc($result)) {
printf $row['firstName'];
echo "----";
printf $row['num_accounts'];
echo "----";
prinf $row['location'];
echo "----";
echo "<br>";
}
}

Related

Querying each element of an array and displaying them as individual data

I have an array which looks like this
"76561198086947554", "76561198133402236"
I need to query each value individually and display the queried data on a page
$pid would be a single value of the array above which I am wanting to query indiviually
$sqlget = "SELECT * FROM players WHERE pid='$pid'";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$name = $row["name"];
echo "<div>
Members: ".$name."
<div>";
}
}
I am happy to try explain it a bit more if you would like me to.
First you use mysql query that have issues with sql injection and is outdated.
Second, if i have understand you need in your WHERE clause the pid value to be in the array you have so your query should be like this:
$your_array = "76561198086947554, 76561198133402236";
$sqlget = " SELECT * FROM players WHERE pid IN ('".$your_array."') ";
// here you check if pid is in array values
... // the other code
Hope it helps and try to convert your code using PDO statements or mysqli.

How to use two different records from database?

I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}

Systemcrash with mysql-object query in while loop

I tried to write my code as short as possible but I discovered something strange here.
If I fetch the query within a 'while loop' the system crashes.
Here's an example.
$sql = 'SELECT * FROM table';
while ($row = $db_ob->query($sql)->fetch_array()){
echo $row['one'];
}
Is this due to my machine or what can I do?
If I write it like my second example, there are no problems
$data = $db_ob->query($sql)->fetch_array()['one'];
This is because you re-run the query on every loop iteration, so it will never end. You need to be sure to only run the query once, then iterate over the results.
$sql = 'SELECT * FROM table';
$result = $db_ob->query($sql);
while ($row = $result->fetch_array()) {
echo $row['one'];
}
Your script execute mysql Query, Retriving datas 'N' times, So you need to rewrite as like,
$sql = 'SELECT * FROM table';
$Result = $db_ob->query($sql);
while ($row = $Result->fetch_array()){
echo $row['one'];
}

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

How to print results in php using AVG and CHAR_LENGTH in MySQL Query

How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...

Categories