This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
There is a table called as 'myTable' which contains columns - MyFactor1, MyFactor2, and MyFactor3. I want to get those column names, but now it returns only 'MyFactor1'. I tried mysql_fetch_array/assoc/object, but they don't work. Could you have any ideas to resolve this? Thanks in advance. Here is my code:
<?php
$aaa = mysql_query("select column_name from `information_schema`.`columns`
where `table_schema` = 'myDB' and `table_name` in ('myTable')");
foreach ($bbb = mysql_fetch_row($aaa) as $taxokey => $taxovalue) {
?>
<option value="<?php print($taxokey);?>"><?php print($taxovalue);?></option>
<?php
}
?>
mysql_fetch_row() returns an array for each row in the result set. Your initial state for foreach calls mysql_fetch_row() once -- it doesn't call mysql_fetch_row() for each row.
So your foreach is not looping over rows, it's looping over elements of the array returned for one row.
Here's a loop that works the way you intend:
while ($bbb = mysql_fetch_assoc($aaa)) {
$taxokey = $bbb["column_name"];
$taxovalue = $bbb["column_name"];
?>
<option value="<?php print($taxokey);?>"><?php print($taxovalue);?></option>
<?php
}
I'm not sure what different strings you intended $taxokey and $taxovalue to contain. All you get from the query you ran is one string, name of each column.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I am sending a sql query to fetch a data from database but the output is showing the column name as it's value. Following are the codes and output respectively:
<?php
include_once("connect_db.php");
$query1 = "SELECT 'first_name' FROM user_details WHERE email='saptakds#gmail.com'";
$result1 = mysqli_query($conn,$query1);
$myArray = array();
while($row = $result1->fetch_array(MYSQLI_ASSOC)) {
$myArray[] = $row;
}
echo '{"maal":';
echo json_encode($myArray, JSON_UNESCAPED_SLASHES);
echo ',"message" : "success"}';
?>
Output:
{"maal":[{"first_name":"first_name"}],"message" : "success"}
The desired output should have been the following:
{"maal":[{"first_name":"Saptak"}],"message" : "success"}
You should remove the ' on SELECT:
SELECT first_name
FROM user_details WHERE email='saptakds#gmail.com'
Explanation: The column name with ' isn't the value of the column, instead it is the value itself. Maybe you it's a mistake and you want to set the backticks instead of '.
This question already has answers here:
How to load MySQLi result set into two-dimensional array?
(3 answers)
Closed 6 years ago.
Looking at all the questions are using the depreciated mysql_fetch_assoc/array, hence I don't think that this is a duplicate question.
I have a MySQL table with 5 columns,
ID | NAME | AGE | GENDER | HEIGHT
If I want to store the values of NAME, AGE, GENDER in a PHP array,
$query=$mysqli->query("SELECT NAME,AGE,GENDER FROM TableName")
while($result = $query->fetch_assoc()
{
$array = [];
}
Will my array be stored in the format of
$array=[[Name,Age,Gender],[Name,Age,Gender]]?
If not, what would be my approach in doing this?
It's very simple. You just have to append the result variable in to main array. Like this,
$array =array();
while($result = $query->fetch_assoc()
{
$array[] = $result;
}
$result is an array (fetch_assoc it returns result-set in array) so just append that into main array to get the desired result. ($array=[[Name,Age,Gender],[Name,Age,Gender]])
$data =[];
$i=0;
while($result = $query->fetch_assoc(){
$data[$i][] = $result;
$i++;
}
This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 1 year ago.
I am working on a recipe site for a school project, and I am trying to echo out two columns of arrays from my database in mysqli.
The arrays look like this:
And when I echo them out I would like them too look like this:
I have literally tried everywhere to find and answer.
My database name is "opskriftreg", and the connection to it works, the rest of the code comes out.
You can use explode to make an array of it,
Example:
$data = "hi,hello,helooo";
$my_array = explode($data);
foreach($my_array AS $value)
{
echo $value."<br />";
}
You are trying to complicate things?! simply get the two columns using a normal MySQL query, and do the job through your language:
select column1, column2 from table;
get the result in a variable of your used language, $array_of_values for example.
for every field in the array explode the value by the delimiter ','.
draw your new table using a loop that goes through the new arrays and write the values in HTML.
For example in PHP:
$array_of_values = array('ing1, ing2, ing3', 'amount1, amount2, amount3');
$ings = explode(',',$array_of_values[0]);
$amounts = explode(',',$array_of_values[1]);
echo "<table>";
for ($i=0; $i < count($ings); $i++){
echo "<tr>";
echo "<td>".$ings[$i]."</td>";
echo "<td>".$amounts[$i]."</td>";
echo "<tr/>";
}
echo "</table>";
This question already has answers here:
php array from mysql
(2 answers)
Closed 8 years ago.
I coded a simple function to loop trough and display all variables in the sql table.
However foreach $row displays the rows two times, 1 time as a row name and 1 time as a row number.
1 : $row['NAME'] Name form
2 : $row[0]' Number form
PHP :
<?php
include "condetails.php";
$query = "select * from pagedetails";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
foreach($row as $var => $val) {
echo "VARNAAM :".$var;
echo "<br />";
echo "VALUE".$val;
echo "<br />";
echo "<br />";
}
}
?>
OUTPUT :
VARNAAM :0
VALUE1
VARNAAM :id
VALUE1
VARNAAM :1
VALUEdddd
VARNAAM :h1txt
VALUEdddd
It's displayed twice because mysql_fetch_array() grabs the column name and its number.
If you want just the column names try using mysql_fetch_assoc(), keep in mind mysql_* functions are depreciated and you should be using PDO / MySQLi :)
mysql_fetch_array returns a mixed array with keys as numbers and as column names. You probably want mysql_fetch_assoc(), which only returns the name keys.
From the manual:
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
What you you're really looking for is mysqli_fetch_assoc():
Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
This question already has answers here:
PHP variable variables
(6 answers)
Closed 1 year ago.
I'm trying to query my database with an array, I'm trying to count the number of rows returned from the query for each country in my database, and also count the rows for each of these countries with a digit equalling 1. Using the following code:
<?php
include ('mysqli_connect.php'); // indclude mysql connection functions
$countries = array('united states','canada','united kingdom');
foreach($countries as $country){
//e.g. $r_spain holds the results from the query below with spain as $country
$r_.$country = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
//loop through the results
while($row = mysqli_fetch_array($r_.$country, MYSQLI_ASSOC)){
$rowCount = mysqli_num_rows($r_.$country);
echo $country."=".$rowCount;
}
}
?>
This is the error message I get:
Catchable fatal error: Object of class
mysqli_result could not be converted
to string in
/home2/designwr/public_html/uwe/notalone/updates/percentage.php
on line 9
Can anybody point me in the right direction?
You are using a string concatenation for your variable name: $r_.$country is the result of the two strings added together.
I would suggest using an array for the result set like:
$r = array(); // after $countries
....
$r[$country] = mysqli_query......
Change:
$r_.$country
to:
${'r_'.$country}
And delete the loop (not it's contents):
while($row = mysqli_fetch_array($r_.$country, MYSQLI_ASSOC))
So in the end the code would look like this:
<?php
include ('mysqli_connect.php'); // indclude mysql connection functions
$countries = array('united states','canada','united kingdom');
foreach($countries as $country){
//e.g. $r_spain holds the results from the query below with spain as $country
${'r_'.$country} = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
$rowCount = mysqli_num_rows(${'r_'.$country});
echo $country."=".$rowCount;
}
?>
References:
http://php.net/manual/en/language.variables.variable.php
http://www.php.net/manual/en/mysqli-result.num-rows.php
I take it line 9 is
$r_.$country = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");
I'm not sure what you're trying to do with $r_.$country = mysqli_query(...); but that's invalid syntax. Use an array:
$r[$country] = mysqli_query(...);
check out the manual on mysqli/query. There you will find simple working examples to get the basics straight. counting is done by the count statement in the SQL-request.