Hi all Im trying to query a database and store the results ($searchResults[]) as an array :
<?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'");
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
}
}
mysqli_close($con);
}
?>
the problem im getting is when I try to echo the result:
<?php
echo $searchResults[0];
?>
its only bringing back 1 result not displaying all the results in the arrray as i want it to.
Could anybody please point out what it is im doing wrong.
Any help would be greatly appreciated
Do like this
<?php
print_r($searchResults); // Prints all array elements
?>
Alternatively, you can make use of a for loop to echo all elements too..
foreach($searchResults as $k=>$v)
{
echo $v;
echo "<br>";
}
Your code puts your data into 1D array. You probably want sth else so instead of this:
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
do this:
$tmp = array();
$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];
$searchResults[] = $tmp;
or just this (thanks to Barmar):
$searchResults[] = $row;
This way you store your data as 2D array. So every row you obtain remains in one subarray.
To print the row (which is now in 2D array) iterate over subarrayw:
foreach($one_of_searchResult_rows as $k => $v)
{
// do whatever you need with $k and $v
}
I think you want a 2d array. Try this code snippet :
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
array_push($searchResults,$row);
}
This should push each row as an associative array in every cell of your final searchResuts array. You could then access the values like:
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result
Lets make it simple :
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);
Reference : mysqli_fetch_all
Related
I'm new to php and would like to know how to make the following possible ...
Below I have several arrays populated from Database rows. Id like to have a new array mappingId that concatenates several rows to form the value for the mappingId array. Below I have used array_combine but this doesn't seem to work. Can anyone advise on what to use?
$appId = array();
$appDate = array();
$appTime = array();
$appDoctorId = array();
$mappingId = array(); // combined values
for ($i = 0; $i < mysqli_num_rows($resultAppointmentsBooked); $i++)
{
$row = mysqli_fetch_row($resultAppointmentsBooked);
$appId = $row[0];
$ids[] = $row[0];
$appTime[] = $row[3];
$appDate[] = $row[4];
$appDoctorId[] = $row[2];
$mappingId = array_combine($row[4], $row[3], $row[2]);
//Test output
echo "MappingId: $row[4]$row[3]$row[2] <br />";
echo "MappingId2: - $mappingId[$i] <br />";
}
I have also used 'array_merge' the following way ...
$ids[] = $row[0];
$appTime[] = $row[3];
$appDate[] = $row[4];
$appDoctorId[] = $row[2];
$mappingId = array_merge($appDate, $appTime, $appDoctorId);
but when I print the values ...
echo "MappingId2: $mappingId[$i] <br />";
It only output the value of the first array.
Try something like this. If this is what you need. Here in the below codes
$mappingId contains array of individual appDate, appTime, appDoctorId in array format. If you don't want array just want concatenate those value with one element then also you can do that. Please let me know!
$mappingId = array(); // combined values
for ($i = 0; $i < mysqli_num_rows($resultAppointmentsBooked); $i++)
{
$row = mysqli_fetch_row($resultAppointmentsBooked);
$appId = $row[0];
$appTime = $row[3];
$appDate = $row[4];
$appDoctorId = $row[2];
$myArr = array();
//array_push($myArr, $appDate, $appTime, $appDoctorId);
// If you want in concatenate format
array_push($myArr, $appDate."".$appTime."".$appDoctorId);
array_push($mappingId, $myArr);
}
You can add values to an array by doing this:
$mappingId[] = 'Hello';
$mappingId[] = 'There';
$mappingId[] = 'Friend';
Results in:
$mappingId = array('Hello', 'There', 'Friend');
--
You can also use array_merge.
This merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
I think what you're looking for is array_merge
array_merge(array(1), array(2,3)); //return array(1,2,3)
try something like this , array_merge should work:
$ids = $row[0];
$appTime = $row[3];
$appDate = $row[4];
$appDoctorId = $row[2];
$mappingId = array_merge($ids, $appTime, $appDate, $appDoctorId);
echo "MappingId: $row[4]$row[3]$row[2] <br />";
echo "MappingId2: - $mappingId <br />";
I have a MySQL database that has a column with a bunch of descriptions. I want those in a PHP array imitating this:
$Description[0] = "Here's a description";
$Description[1] = "Here's another description";
$Description[2] = "Wow, many descriptions";
$Description[3] = "Another one";
$Description[4] = "They just keep going";
...etc
I'm struggling with the while loop logic to make this happen though. Help!
$result = mysql_query(...);
$Description = array();
while ($row = mysql_fetch_array($result)) {
array_push($Description, $row["columnyouwant"]);
}
$Description = array();
$result = mysql_query(......);
while ($row = mysql_fetch_array($result))
{
$Description[] = $row;
}
// echo print_r($Description);
hi very simple...
foreach ($Description as $value) {
echo $value;
}
Newbie to PHP and trying to learn it. I have returned data from my DB.
So the rows may look something like below
ID--------Name--------PhoneNo
1 Joe 1234
2 Jane 5678
3 Tom 0000
I am using the msql_fetch_array to return the data as below:
<?php
while($row = mysql_fetch_array($result))
{
$NameOne = $row['Name'];
}
?>
This is placing the name 'Joe' in the variable name NameOne as expected. What is the best way however to get Jane and Tome into variables called $NameTwo and $NameThree that I can then echo these variables further down in my html and similary I want to place the phone number retrieved into seperate variables and refer to them later in my html.
The ideal approch will be saving them inside an array, which can be achieved like this:
$Names = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$Names[$i] = $row['Name'];
$i++;
}
Now you can retrieve your data this way:
echo $Names[0]; // Will output the first name saved.
Rather than creating so many new variables, why not create an array?
<?php
$i=1;
while($row = mysql_fetch_array($result))
{
$Names[$i]= $row['Name'];
$i++;
}
?>
You can then use the array in your code
echo $Names[1]; // 1 or 2 or 3 etc
For multiple attributes you can use a multidimensional array
$i=1;
while($row = mysql_fetch_array($result))
{
$Data[$i]["Name"]= $row['Name'];
$Data[$i]["Phone"]= $row['Phone'];
$i++;
}
You can then use the array in your code
echo $Data[1]["Name"]; // 1 or 2 or 3 etc
If you want to really persist the results, store them in an array:
<?php
$data = array();
// Note that I've changed "mysql_fetch_array" to "mysql_fetch_assoc" to decrease the number of saved data.
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['Name'];
}
/* Now you can use the data wherever you want, like: $data[0]['Name'] for first name, $data[1]['Name'] for second name and so on */
?>
To strictly answer KOL's question:
<?php
$i = 0;
$numbers = array('One', 'Two', 'Three', 'Four', 'Five');
while($row = mysql_fetch_array($result)) {
if($i++ > count($numbers) {
throw new NotMoreNumbersSupportedException();
}
$varname = 'Name' . $numbers[$i++];
$$varname = $row['Name'];
}
var_dump($NameOne, $NameTwo, $NameThree, $NameFour, $NameFive); //etc
?>
Now shoot me.
You can directly place html inside your while loop
<?php
while($row = mysql_fetch_array($result))
{
?>
<div><?php echo $row['Name']; ?> </div>
<div><?php echo $row['PhoneNo']; ?> </div>
<?php }
?>
You can add the details to another array
<?php
$names = array();
$phnos = array();
while($row = mysql_fetch_array($result))
{
$names[] = $row['Name']; //$names[0] , $names[1] etc..
$phnos[] = $row['PhoneNo']; //$phnos[0] , $phnos[1] etc..
}
?>
I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}