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

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.

Related

multiple mysql query result in single array

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>";
}
}

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.
}

Select row of information for each array element

I have this bit of code that doesn't produce anything, not even an error message. I'm trying to echo the result inside the while loop, but even that doesn't show anything. Any tips?
foreach($droppedStudentIds as $value){
$query3 = "select * from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists)";
if($result = mysqli_query($mysqli, $query3)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "Date: ".$row['ClassListDate'];
$droppedStudentIds[$value][] = $row['ClassListDate'];
}
mysqli_free_result($result);
} else die ("Could not execute query 3");
}
My goal is to look up a date information for each element inside the $droppedStudentIds array. I checked the MySQL query in itself and it produces that desired result.
Thanks!
You're assigning to the array you're looping through on this line:
$droppedStudentIds[$value][] = $row['ClassListDate'];
This could be causing your script to timeout, which would be why you're not seeing any output.
I'd add a second array to avoid conflicts and use that for storing results from the query, e.g.
$temp[$value] = $row['ClassListDate'];
Thanks all for the response, it helped pin down the mistake!
No need for a while loop when asking for a single record
The query was actually incorrect. The subselect was getting the maximum date in the database, regardless of whether the StudentId was present or not. The correct query is the following:
select ClassListDate from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists where StudentId = '$value')
Thanks again!

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...

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories