Loop through fetchall without knowing the fields php - php

I have a simple query which will fetch all from a users tables
$query = $this->pdo->prepare('SELECT * FROM `users`');
$query->execute();
return $query->fetchAll();
Then i would have a foreach loop like
$results = $User->getUser();
foreach($results as $result){
echo $result['fname'];
echo $result['lname'];
}
But is there a way to display each of the fields without writing each field name?

First, fix your return fetchAll to specify the return style like so:
return $query->fetchAll(PDO::FETCH_ASSOC);
Then you can use an inner loop with your outter loop like so:
//get the results
$results = $User->getUser();
//loop over the results, setting $result to an array representing each row
foreach($results as $result){
//loop over each $result (row), setting $key to the column name and $value to the value in the column.
foreach($result as $key=>$value){
//echo the key and value.
echo "{$key} = {$value}<br>";
}
}
This will output all columns and their value regardless of what columns there are in the array. Following the comments, you can see what I do is, using your code, loop over the outer array that is an array of each row from the query. Then loop over the array from each row getting the column name and the value in that column. For now I am just echo'ing out the column and value. You would likely want to do more like echo this out to a table or whatever your end goal is.

Related

Why PHP Mysql query inside a foreach loop always returns the first result from database?

I'm trying to run a MYSQL query inside a foreach loop.
here's the scenario:
I have a comma separated string with some names in it.
I use explode() and foreach() to get the separate values/names from this comma separated string.
Then I need to search mysql database for each of these values/names that I get from this string and if that value exists in the database, I then get its ID and create a new recrord in another table in the database.
However, when I run my code, I only get the ID of the first instance from the comma separated string.
my mysql database looks like this:
id category_name
3 Hotel
4 Restaurants
This is my code:
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
///i do the explode and foreach here///
$arrs = explode(',', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
}
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>;
}
so when the i run my code, I get the ID of the Hotel twice like so:
3
3
I'm expecting it to be like below based on what I have in MYSQL:
3
4
Could someone please advice on this issue?
First of all such things should be done using prepared statements. Not only it is easier and faster, but also more secure. Remember to always use prepared statements.
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
$stmt = $db_conx->prepare('SELECT * FROM categories WHERE category_name=?');
$stmt->bind_param('s', $cat);
foreach(explode(',', $biz_cat) as $cat){
$cat = trim($cat); // remove extra spaces at the beginning/end
$stmt->execute();
// we fetch a single row, but if you expect multiple rows for each category name, then you should loop on the $stmt->get_result()
$row99 = $stmt->get_result()->fetch_assoc();
// echo it in the loop or save it in the array for later use
echo $row99['id'];
}
In the example here I prepare a statement and bind a variable $cat. I then explode the string into an array on which I loop straight away. In each iteration I execute my statement, which in turn produces a result. Since you seem to be interested only in the first row returned, we do not need to loop on the result, we can ask for the array immediately. If you would like to loop just replace
$row99 = $stmt->get_result()->fetch_assoc();
with
foreach($stmt->get_result() as $row99) {
echo $row99['id'];
}
Once you get the id in the array, you can either print it out or save it into an array for later use.
As of now, you are re-assigning a new value to scalar variable $catIDS for each record returned by the query, then you echo it one you are done looping. You would need to put the echo/insert logic inside the loop (or maybe store the values in array).
Another thing to note is that you are splitting with , (a single comma), but you have a space between the two words. As a result, the second value (Restaurant) starts with a space, which will cause the query to return an empty resultset. You probably want to split with , (a comma followed by a space).
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(', ', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>';
}
}
The code below can do what you need.
Update INSERT YOUR NEW DATA HERE
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(',', $biz_cat);
foreach ($arrs as $arr) {
$query99 = mysqli_query($db_conx, "SELECT * FROM categories WHERE category_name='$arr'");
while ($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)) {
$catIDS = $row99['id'];
// INSERT YOUR NEW DATA HERE
echo $catIDS . '<br/>';
}
}

Mysqli prepared statement: store rows in an array and loop through this array later

I use a prepared statement to select rows in a database. Subsequently I would like to echo the individual rows using a while loop. This worked fine, until I tried using a new query within the execution of the while loop (this was necessary because I extract the userID, which I need to transform into a username. I did this by performing a query on the users table, but when I try this, my code doesn't run). I thought I might fix this by storing all the rows in an array, and later in my code loop through this array. However, I can't seem to figure out how to loop through all indices of this array and extract all fields of the row in each instance of the loop.
Thanks a lot! Here is my code:
$results = array();
$stmt = $db->prepare("SELECT admissionID,userID,description,link,postingdate,compensation FROM replies WHERE projectID=?");
$stmt->bind_param('i',$projectID);
$stmt->execute();
$stmt->bind_result($admissionID,$userID,$description,$link,$postingdate,$compensation);
while($row = $stmt->fetch()){
$results[] = $row;
}
foreach($results as $result) {
echo $result['admissionID'];
}
This is how you need to do it
ids=array();
while($row = $stmt->fetch()){
ids[]= $row['userID'];
}
ids is an array and will have all the ids that you need.
But I would say "Dont do it like that", just use a table join to get the username for example may be your case would be like
SELECT replies.admissionID,users.name,replies.userID,replies.description,
replies.link,replies.postingdate,replies.compensation FROM replies, users
WHERE
users.name=replies.userID
and replies.projectID=?

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

two keys one value pdo query result

my code is this
$sql = "SELECT * FROM faculty";
foreach ($pdo->query($sql) as $row) {
foreach ($row as $key => $value) {
echo $key."-".$value."<br/>";
}
}
it's fairly simple what i'm doing. My question is why am i getting the same value
two times, one with a key the name of the row in mysql (e.g "surname") and one the position of the array.
Thank you for your time.
That's because your default fetch mode is set to
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0. Try e.g.
$pdo->query($sql, PDO::FETCH_ASSOC)
instead.
see also: http://docs.php.net/pdo.constants

return variables from array using a function

I retrieve data from database using this query:
SELECT * FROM tickets_departement_groups WHERE group_id = '{$user_group}'
$user_group is already defined, and I fetch the data using mysql_fetch_array, like this:
foreach ($query->result_array() as $row)
{
return $row['departement_id'];
}
All this is under a function called get_departement_id(), So when I do echo get_departement_id();
it prints last departement ID, but I have many of them. What I want to do is to output all the department IDs for a given query.
create and array and return the array?
$id_list = array();
foreach($query->result_array() as $row){
$id_list[] = $row['departement_id'];
}
return $id_list;

Categories