Actually with my code I print out all results together but the goal is to associate to a variable each row.
$sql = "SELECT modello FROM THING;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["modello"]; //this print all result but want to associate first result to variable $first and second to $second
}
} else {
echo "0 results";
}
Change echo $row["modello"]; to $modellos[] = $row["modello"]; like so in the example below:
$result = $conn->query("SELECT modello FROM THING");
$modellos = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$modellos[] = $row["modello"];
}
} else {
echo "0 results";
}
Now $modellos has the first in $modellos[0] and the second in $modellos[1] and the third in $modellos[2] etc etc to do with as you wish after the while loop. If you really really need them in $first and $second, add after the loop:
$first = $modellos[0];
$second = $modellos[1];
You can use array to store your results.
$result = []
while($row = $result->fetch_assoc()) {
$result[] = $row["modello"];
}
But if you really need to associate each row to a variable, you can use:
$i = 0;
while($row = $result->fetch_assoc()) {
${"result" . $i} = $row["modello"];
$i++;
}
Related
Good day!
I have a problem here that I can't solve (last 5hrs).
here's my codes:
include 'assets\function\retrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
$loadGradProgram[$i] = getCourseInfo();
}
echo $loadGradProgram[0];
getCourseInfo function
Solution 1:
function getCourseInfo(){
$getInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
return $getInfo;
}
}
Result: Array to string conversion
Solution 2:
function getCourseInfo(){
$getInfo = array();
$loadInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
$conn->close();
for($x,$x<=$i;$x++;){
$loadInfo[] = implode(',', $getInfo[$x]);
}
return $loadInfo;
}
}
Result: Still the same
and this line causing error: echo $loadGradProgram[0];
I use echo just to see if the query is working.
if you want a multi-dimmentional array like in w3c documentation, you do it like this :
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i][] = $row['courseID'];
$getInfo[$i][] = $row['courseCode'];
...
$i++;
}
return $getInfo;
then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :
foreach($loadGradProgram as $key => $value) // here the key is useless
{
echo $value[0];
echo $value[1];
}
or directly like this :
echo $loadGradProgram[0][0];
echo $loadGradProgram[0][1];
echo $loadGradProgram[1][0];
I want to access while array $row2 outside the loop so that I can compare in if else condition, because $row2 array contains many number. Is there any solution make $row array accessible outside the loop or any other method?
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($query)) {
$row2 $row['id'];
}
for($i=1;$i<=10;$i++) {
if ($i<= $row2) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
continue;
} else {
echo $i.'<br>';
}
}
?>
If you want to loop over two dependent things you need to nest them or else $row2 will always contain the last value in the while loop:
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($query)) {
$row2 = $row['id']; // I added an = sign here.
for($i=1;$i<=10;$i++) {
if ($i<= $row2) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
continue;
} else {
echo $i.'<br>';
}
}
}
If this isn't what you want please clarify your question.
Pass your variable to a separate function that performs whatever task you want.
<?php
while($row = mysqli_fetch_array($query))
{
MyFunction($row2);
}
function MyFunction($passed_row2_value){
// perform whatever task you want here.
}
?>
This shows with some format the ids retrieved by the query and fills the blanks without format.
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
$row2 = [];
while($row = mysqli_fetch_array($query)) {
$row2[$row['id']] = true;
}
for($i=1;$i<=10;$i++) {
if ($row2[$i]) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
} else {
echo $i.'<br>';
}
}
?>
By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);
I have the following code:
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings WHERE location = '$locationListResults' AND industry = '$selected'");
while($row = mysqli_fetch_array($results))
{
echo $row['industry'];
echo $row['location'];
echo $row['title'];
echo $row['description'];
}
}
mysqli_close($con);
}
?>
Could anyone tell me how I would go about storing the echo part into a variable so I can then display it as and where I want in other parts of the site?
If I remove the echo and instead store $row as a variable when I echo that variable it only outputs once and doesn't run the loop.
You should use mysqli_fetch_all for this. The result will be an array where each element is a row and each row is an associative array with the same keys as row in your example
$data = mysqli_fetch_all($result);
$data[0]["industry"]; //Data in the first row
You can then loop over $data to output it any place on your page.
put in array,
$list = array();
while($row = mysqli_fetch_array($results))
{
$list[] = $row;
}
you may try this
$arrayList = array();
while($row = mysqli_featch_array($results)){
$arrayList[] = $row;
}
print_r($arrayList);
Put all the values in an array
$rows = array();
$x = 0;
while($row = mysqli_fetch_array($results))
{
$rows[$x]['industry'] = $row['industry'];
$rows[$x]['location'] = $row['location'];
$rows[$x]['title'] = $row['title'];
$rows[$x]['description'] = $row['description'];
$x++;
}
return $rows;
Then you can use $rows as an array.
foreach($rows as $v){
echo $v['industry']." ".$v['location']."<br />";
echo $v['title']." ".$v['description']."<br />";
}
The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>