I am trying to create a PHP function that will echo info from a db. My col names look like banana[1], banana[2], apple[1], apple[2], apple[3], and so on.
The function will select the fruit
function fruits($fruit){
}
and then within that function I'll loop through the fruits.
How do I echo these?
echo $fruit[$i];
obviously doesn't work.
Pretty basic, but I can't figure out. Concatenation kills me.
function ponctuation($section,$sect){
switch($section){
case 'apple':
$i=1;
break;
case 'banana':
$i=13;
break;
}
global $mysql_tablename;
global $FName;
global $Lname;
if(isset($mysql_tablename)){
$result = mysql_query("SELECT * FROM $mysql_tablename WHERE FName='$FName' AND Lname='$Lname'");
$row = mysql_fetch_array($result);
echo '<form method="post" action="ponctuation.php?'.${$section.$sect}.'_valider">';
echo '<ul>';
$query = mysql_query("SELECT * FROM `ponct_enonces` WHERE `section`='$section' AND `sect`='$sect'");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['enon']==0 && $row_q['senon']==0){
echo '<h2>'.$row_q['enonce'].'</h2>';
}
if($row_q['enon']==1){
echo '<h3>'.$row_q['enonce'].'</h3>';
echo '<textarea rows="3" cols="100" name="'.$i.'" wrap="physical">' . $row[$section[$i]] . '</textarea>';
}
if($row_q['senon']==1){
echo '<h4>'.$row_q['enonce'].'</h4>';
echo '<textarea rows="3" cols="100" name="'.$i.'" wrap="physical">' . $row[$section]. '</textarea>';
}
$i++;
}
echo '</ol>';
echo '<input type="submit" name="submit" value="Valider"/>';
echo '</form>';
}
}
The code is a little ugly, and some vars have French names, other have English names.
col names won't be expanded into PHP array structures for you, e.g.
SELECT fruit[1], fruit[2], ...., fruit[100]
will give you the equivalent of
$row = array(
'fruit[1]' => someval,
'fruit[2]' => someval,
...
);
if you want to iterate those, you'll have to get ugly:
$fruit = array();
for ($i = 0; $i <= 100; $i++) {
$fruit[$i] = $row['fruit[' . $i . ']'];
}
which begs the question of... why? This is a horrible data structure to be using. Properly normalizing it into a 'fruit attributes' sub-table would save you this trouble, and also allow you to have n attributes, rather than the fixed 1..100 range or whatever it is you have.
If you're attempting to loop over all the columns in a row, you can use fetch_array:
$result = $mysqli->query($query);
$row = $result->fetch_array();
// loop over columns
for ($i = 0, $count = count($row); $i < $count; $i++)
echo $row[$i];
That way, you won't have to worry about the column names. I might be misunderstanding your question, though.
Related
I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?
The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}
Eureka! It worked. I just had to change the line for the values to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.
I have a file with 20 pictures of country artists, and a text file with their websites. I'm trying to display this data in a 4 row 5 column table using PHP.
I try to use a foreach loop that iterates for every 5 elements in the array
(to load each row one by one)
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
<table>
<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td></tr>
</table>
Ive been trying to figure out how to load the images into the array, but having no luck. Im starting to think i must put the reference to the file location in the array,but i am not sure.
$colsToDisplay = 5;
$CountryArtists = array("C:\Users\THEFOLDER\images");
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", RTravis", "STwain", TKeith", TMcgraw");
$filename = "C:\Users\THEFOLDER\images";
I'm relatively new to PHP and really just need to know how to load my images and how to make this table show up correctly.
EDIT:
I added echo to the table lines but it just shows echo in the browser output:
" echo " $CountryArtists[$Value] $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo "" } ?>
My code now looks like this:
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
echo "<table>"
echo "<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td></tr>"
echo "</table>"
}
I feel like I'm doing strong wrong, would be so grateful to have it pointed out to me.
FULL FILE
<!DOCTYPE HTML>
<html>
<body>
<?php
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
$count = count($ArtistImages);
$cols = 6;
$div = (int) $count / (int)$cols;
$diff = ceil($div);
echo
$fin = $cols * $diff;
$a = 1;
echo '<table>';
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
?>
</body>
</html>
I think you may be looking for something similar to this algorithm. It adds a row every 5 values. You will want to do a divisor make it ceil() to make it add any required empty cells. You can do this foreach if you do <ul> and <li> and use CSS to make them display like a table. Then you don't need to calculate extra cells.
$i = 1;
echo '<table>';
foreach($array as $value) {
if($i == 1)
echo "<tr>";
echo '<td>'.$value.'</td>';
if($i == 5) {
echo "</tr>";
$i=0;
}
$i++;
}
echo '</table>';
EDIT:
Here is a more practical version based on yours:
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
// Count total artists in array
$count = count($ArtistImages);
// Choose how many to display per row
$cols = 6;
// Divide the total by the columns
$div = (int) $count / (int)$cols;
// Round up (incase the number will produce empty cells
$diff = ceil($div);
// Mulitply the final numbers
$fin = $cols * $diff;
// Create an autoincrementer to keep track of next rows
$a = 1;
echo '<table>'.PHP_EOL;
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
// You need to see if this artist is populated. If not, make empty
// If left without this it will have a warning saying not exists
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
In the php file you need to echo the data you want.
However if you in the php file you can close php like this.
? >
And write html code.
When you want to display php attributes you again need to open a php like this:
and continue like this...
Php fcan only return string or json data
Let me know if it work for you....
I'm having an issue with the code below, I want to test a user's input against values in a text file. The output of the code works only for the last element of the array (each value of the text file is stored as an element of an array) which succeeds in correctly comparing the input against the array element, however when entering any other element in the array, no 'match' is being made. I want all values to be numeric and only one same value to exist, if more than one, output an error. Thanks guys :)
array.txt has the following contents
11111
22222
33333
44444
PHP:
<?PHP
if (isset($_REQUEST['attempt'])) {
$users = file('C:/wamp/www/php/comparision/array.txt');
$input = $_POST['input'];
print "Results:";
print '<br></br>';
$x = count($users);
print '<br></br>';
print '<br></br>';
$i = 0;
while ($i < $x) {
print $users[$i];
print $input;
$truevar = NULL;
$arrayelement = $users[$i];
if ($input == $arrayelement) {
print '<p>';
echo " It is in the array";
print '</p>';
$truevar = $truevar + 1;
}
else if ($input != $arrayelement) {
print '<p>';
echo " Nope";
print '<p>';
}
print '<br></br>';
$i = $i + 1;
}
//Check entries
if ($truevar > 1) {
print '<br></br>';
echo "Multiple entries";
}
else if ($truevar == 1) {
print '<br></br>';
echo "Comparison success";
}
else if ($truevar < 1) {
print '<br></br>';
echo "Comparison not successfull";
}
}
?>
<p>Please enter data</p><br></br>
<form action="compare.php?attempt" method="post"/>
<input type="text" name="input" size="15" value="" />
<input type="submit" name="carddata" value="Submit"/>
</form>
Use:
$users = file('C:/wamp/www/php/comparision/array.txt', FILE_IGNORE_NEW_LINES);
Without that option, the newlines that separate the lines in the file are included in the values in $users, so the comparisons fail.
The problem seems that you set $truevar = NULL; inside the while loop. Like this, the variable always gets reset to NULL with every loop.
You should be fine if you move the $truevar = NULL above the while-line
I am creating an in-house order pulling application. I'm pulling form an ODBC source and placing items in an array. I'm then creating a new flat file for each order being physically worked on. When the user scans/enters an item from that order number it places that item on a new line in the order file that was created.
I'm then reading that order file back to get the items that have been scanned thus far. Where I'm stuck is how to mark that line item that exist in the order file as being completed in the HTML table.
Here is the pertinent code as it relates to my question:
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array("$itemno_array[$i]", $items_array)) {
echo "<td>$itemno_array[$i] EXISTS</td>";
}
else {
echo "<td>$itemno_array[$i] NO EXIST</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";
As you can see I'm iterating through the array and displaying it in a HTML table. I'm curious why my above code isn't working. My result ends up being from the 'else' statement thus ALL lines, even if they exist in the file is showing as "NO EXIST" which is obviously incorrect.
Can you post your Print_r($items_arr);
also try using isset($arrayVar[$key]
and try removing double quotes and see if it works.. like ...
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array($itemno_array[$i], $items_array)) {
echo "<td>".$itemno_array[$i]." EXISTS</td>";
}
else {
echo "<td>".$itemno_array[$i]." NO EXIST</td>";
}
// echo "<td>".$location_array[$i]."</td>";
echo "<td>".$qty_array[$i]."";
echo "<td>".$pickingseq_array[$i]."</td>";
echo "</tr>";
}
echo "</table>";
I got this resolved by going about it a different way. I use strpos() to search the flat file itself rather than the array that I exploded from it:
echo "<table>";
//for ($i = 0; $i < count($itemno_array); $i++)
for($i=0;$i<sizeof($itemno_array);$i++)
{
echo "<tr>";
// if (in_array($itemno_array[$i], $items_array)) {
echo "<td>";
$var = $itemno_array[$i];
$newvar = trim($var);
if(strpos($file_array, $newvar ) !==FALSE) {
echo "$var ** EXISTS</td>";
}
else {
echo "$var DOES NOT EXIST **</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";
I'm really stuck trying to resolve what should be quite simple.
I Have this
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$id = array('33540116', '33541502');
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
So the code is decoding a json string then using foreach to echo each result.
This json file is rather large and I'm only interested in certain records that match the id's stored in a mysql table.
To do this I have replaced the id array string above with mysql select statement.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$row = mysql_fetch_array($result);
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Although this works, it only gives me 1 result.
What I really need is to loop through the results.
Unfortunately I don't know how to construct a while loop together with foreach.
I will greatly appreciate your assistance.
UPDATE (extra question)
Thanks everyone. You have helped me solve the problem.
However, I have another question that relates to this matter.
I mentioned above that I merely wanted to echo the results.
But this isn't exactly true.
What I really want to do is update the same mysql table with the results retreived from the json file.
I have a table called people with fields id, name and age.
How can I update this table with these results?
Thanks again.
mysql_fetch_array only fetches one row at a time. You can use a while loop to continue fetching rows. The mysql_fetch_array function returns false once the whole result set has been fetched, so that will cause the while loop to terminate as desired.
Also, I removed the foreach loop on $ids. Since there will only be one element in the array it's unnecessary to put the code in a loop.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
while ( ( $row = mysql_fetch_array($result) ) ) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Try this:
while($row = mysql_fetch_array($result)) {
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
}
You are using this :
$row = mysql_fetch_array($result);
This will only fetch one row from the database.
If you want to fetch more than one row, you have to call mysql_fetch_array() in a loop :
while ($row = mysql_fetch_array($result)) {
// Work with the current row
}
In your case, you'd have something like this :
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
You do not need foreach loop the while is just enough
$result = mysql_query("SELECT id FROM people");
$id = array($row['id']);
while($row = mysql_fetch_array($result))
{
echo $json->$row['id']->person->{'name'}. '<br />';
echo $json->$row['id']->person->{'age'}. '<br />';
}
You have a couple of issues. Firstly, you shouldn't be using foreach($id as $id) since you are using the same variable for both. Instead it should be foreach($ids as $id). Secondly, you can get a list of the ids and echo out the correct json values as follows
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row['id'];
}
foreach($ids as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Hopefully that will solve it