echo array as column mysqli? [duplicate] - php

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

Related

IF statement doesn't work within while loop - not sure if the conditions are right? [duplicate]

This question already has answers here:
How to check if a string is one of the known values?
(4 answers)
Closed 3 years ago.
I'm trying to echo entries from a database that have a lend_status of 1 or 2 and have written my while loop to get the entries but I'm not sure if my IF statement is correct or if this is the best way to go about this. I'm very new to PHP and SQL so any help would be really appreciated!
I've tried using an echo to see where it breaks and it seems to be the IF statement. I know the connection to the database works as I can echo information from it and have tested that.
<?php
// WHILE LOOP TO LOOK THROUGH THE DIFFERENT ROWS
$STH = $DBH->prepare("SELECT * FROM laptop_system");
// DOESN'T HAVE TO BE AN ARRAY BUT GOOD PRACTICE TO PUT THIS IN (BELOW)
$STH->execute(array());
// WHILE LOOP TO LOOK THROUGH THE DIFFERENT ROWS
while ($row = $STH->fetch()) {
$lend_status = $row->lend_status;
$lend_id = $row->lend_id;
$requestee = $row->user_id;
$first_name = $row->first_name;
$last_name = $row->last_name;
$active_status = array(1,2);
if($lend_status == $active_status) {
echo 'hello';
?>
<div>
<?php echo $requestee_name . '\n'; ?>
<?php echo 'hi'; ?>
</div>
<?php }} ?>
The problem is that you are comparing a string / integer - one of the fields of your database row - to an array:
$lend_status = $row->lend_status;
...
$active_status = array(1,2);
if($lend_status == $active_status) {
If you want to check if the status is one of the values in the array, you can use for example in_array():
if (in_array($lend_status, $active_status)) {

How to find out automatically the numeric index of an specific MySQL column in PHP?

I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )

PHP foreach row as $var, row name and row number duplicate [duplicate]

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.

How can I get column names from mysql? [duplicate]

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.

php / mysql select- this is an easy one

I have this code.
<?php
require('connection/conn.php');
mysql_select_db($db_name,$ligação);
//$rsArticle = mysql_query("CALL get_article(1,518)");
$rsArticle = mysql_query("SELECT * FROM tblarticles WHERE ArticleID = 518");
while($rowArticle = mysql_fetch_array($rsArticle)){
echo $rowArticle;
}
?>
And instead of getting the text that exists in the database I just get the word: Array
The line that is commented its for calling a stored procedure. In a desperate measure I made a simple select, in the next line
Can anyone explain me what I'm doing wrong??
Thanks
The reason that you are getting the word Array is because what you are echoing is an Array. Use something like echo $rowArticle['column-name']; to echo the data from a specific column of your query.
You can't echo an array. try print_r() instead
if you want the values individually, do something like this:
while ($row = mysql_fetch_array($rsArticle, MYSQL_NUM)) {
//echo the first column of the record (index 0)
echo $row[0];
}
look in the php.net documentation for more info
mysql_fetch_array returns an array with elements for every field in your database table.
Either print the whole array with print_r() or use echo $rowArticle[COLOUMN_NAME] to echo certain values from your resultset.
mysql_fetch_array() returns you the array, when you use echo is actually return the object type in case of array.
use print_r($rowArticle); instead of echo.

Categories