Abort "for", when after array is empty - php

i have the var $products who reads the id and twelve products from a mysql row in a array. No i want that only the fields who have text will be displayd. I wrote it with a "for" and it works, but how can i tell the code to stop, after the array is getting empty? "p" is to generate the db field name who is p1, p2 and so on.
for($i=1; $i < count($products); $i++)
{
echo "<div>Produkt ".$i":</div>
<div>".$products["p".$i]</div>"
}

Are you looking for something like this:
<?php
for($i=1; $i < count($products); $i++)
{
if($products["p".$i] !=""){
echo "<div>Produkt ".$i.":</div>";
echo "<div>".$products["p".$i]."</div>";
}
}
?>

Related

Loop through all check boxes, weather it is checked or unchecked in PHP

My problem is that the below code changes the value of the checked ones, but the index i is assigned to the checked ones only. I want it to pass through all check boxes. For examples if the first and last check boxes were checked, I am getting job[0] is "yes" and job[1] is "yes" and the rest are "no" while I should get "yes" for job[0] and job[4].
Code below:
if(!empty($_POST['job'])){
$i = 0;
$jobArray = array("no","no","no","no","no");
// Loop to store and display values of individual checked checkbox.
foreach($_POST['job'] as $selected){
$jobArray[$i] = "yes";
$i++;
}
} //$_POST['job']
The thing is that checkboxes values exist in your request only if they are checked. You should keep it in mind.
So, you can change your application logic to work with that. But if you really need to have an array with 'yes', 'no' values, just create it.
Let's say you create your checkboxes like so:
<?php for ($i = 0; $i < 10; $i++): ?>
<input type="checkbox" name="job[<?= $i ?>]" value="yes">
<?php endfor; ?>
Then, in your code:
$jobs = [];
for ($i = 0; $i < 10; $i++) {
$jobs[$i] = $_POST['job'][$i] ?? 'no';
}

insert using multiple foreach inside for each only gets the final value in every foreach

I am currently working on a evaluation system. The questions are dynamically created/
So I already tried insert values from different foreach of input fields I use input type text instead of radio button. my code is just inserting the last value get from each foreach loop.
<?php
session_start();
include('connectDB.php');
$userId= $_SESSION['id'];
mysqli_query($conn,"UPDATE student SET evaluationId = 1 WHERE studentId='$userId'");
foreach($_POST['nPersonnelId'] as $personnelId ){
for ($i=0; $i<count($_POST['rCourteous']); $i++){
$rCourteous = $_POST['rCourteous'][$i];
}
for ($i=0; $i<count($_POST['rPrompt']); $i++){
$rPrompt = $_POST['rPrompt'][$i];
}
for ($i=0; $i<count($_POST['rCompetent']); $i++){
$rCompetent = $_POST['rCompetent'][$i];
}
for ($i=0; $i<count($_POST['rAccom']); $i++){
$rAccom = $_POST['rAccom'][$i];
}
mysqli_query($conn,"INSERT INTO qpanswer
(studentId,personnelId,courteous,prompt,competent,accommodating)
VALUES ('$userId','$personnelId','$rCourteous','$rPrompt','$rCompetent','$rAccom')");
}
header('location:studentDashboard.php');
?>
You don't need all of the inner loops, just get the index from the outer loop and use that for all of the inner arrays. So here get $i from the foreach key...
foreach($_POST['nPersonnelId'] as $i => $personnelId ){
$rCourteous = $_POST['rCourteous'][$i];
Same for each of the other fields.
Also as pointed out - use prepared statements.

list mysql data in 3 columns alphabetical vertical

I have this statement that works fine, but list alphabetical from left to right across 3 columns. I want it to list alphabetical vertically down the column and then continue onto the next column. Anyone know how I can do this.
$models = mysql_query("SELECT model, id FROM model where make='$phonemake' order by model asc") or die(mysql_error());
$count = 0;
$max = 3;
while($model = mysql_fetch_array( $models ))
{
$count++;
echo "<div style='float:left; width:31%; padding-right:5px;'>".$model['model']." <a href='include/delete-model.php?id=".$model['id']."' onclick='return makesure".$model['id']."();'>Delete</a></div>";
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo"<div style='clear:both;'></div>";
You have two options:
You can buffer result into array and change the order of adding of divs
The code could look like this:
$allmodels = array();
while($model = mysql_fetch_array( $models ))
{
$allmodels[] = $model;
}
for($i = 0; 3 * $i < count($allmodels); $i++)
{
for($j = 0; $j < 3; $j++)
{
if(isset($allmodels[($i * 3) + $j]))
{
$model = $allmodels[($i * 3) + $j];
// print your stuff here...
}
}
}
Or you can somehow reorder items in the sql query, maybe dump that to the temporary table or play with mysql_data_seek.
echo the data in a UL LIST , and use your counter to set the number of rows in the UL LIST , when counter is reaches max, create a new list and continue displaying. Personally i would use:
if($counter%3==0) {
create new list
}
this way you dont need to reset the counter everytime.

Dynamic text fields values into PHP array

I have a dynamic web form that creates text after the user tells it how many he wants, what I want to do, is to get the info of those text fields into the next form, I've read a question that is
pretty much what I want to do;
But I haven't had any luck so far;
for ($i = 1; $i <= $quantity; $i++) {
echo "<input type='text' class='text' name='classEmpleado[]' id='empleado$i' />";}
When I try to retrieve them I use this;
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 1; $i <= $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
But I get the error Undefined index: classEmpleado[]
What am I doing wrong?
ANSWERED!
For anyone looking for the same thing, look at the response of Sherbrow,
And you would just have to edit the loop to this
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 0; $i < $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
If $empleado is not previously declared or just empty, you are looking for that
$empleado = $_POST['classEmpleado']
But if $empleado is an array, and contains data, you may want to merge everything in one only array
$empleado = array_merge($empleado, $_POST['classEmpleado']);
Whichever way you choose, there should be a check to be certain that $_POST['classEmpleado'] is defined and is an array. Something like :
if(isset($_POST['classEmpleado']) && is_array($_POST['classEmpleado'])) {
/* ... */
}
Try $empleado[] = $_POST['classEmpleado'];
When you put name[] at the end of the fieldname, it will be passed to PHP as an array in $_POST with the key of name like so: $_POST['name'] = array(1,2,3,4);
This statement here is wrong ($empleado[] = $_POST['classEmpleado[]'])
If you want to access $_POST the input field named classEmpleado[], you have to do so :
for($i=0; $i<count($_POST['classEmpleado']); $i++)
{
echo $_POST['classEmpleado'][$i] . '<br /><br />';
}

Problem looping through usernames

I am trying to loop through an array of usernames and for each username, execute a mysql_query on each.
<?php
for ($i = 0; $i < count($u); $i++)
{
$j = $i + 1;
$s = $database->checkUserPlayedRecent($u);
if (mysql_num_rows($s) > 0)
{
?>
<tr>
<?php
echo "<td>$j</td>";
?>
<?php
echo "<td>$u[$i]</td>";
?>
<?php
echo "<td>$p[$i]</td>";
?>
</tr>
<?
}
}
?>
As you can see, $u is each username.
I want each username to only appear in the echo statements if each one has num_rows > 0.
At the moment nothing is displaying.
But there should be results being returned!
Can someone help please.
The sql:
$q = "SELECT id FROM ".TBL_CONF_RESULTS." WHERE (home_user = '$u' OR away_user = '$u') AND date_submitted >= DATE_SUB(CURDATE(),INTERVAL 14 DAY)";
This line :
for ($i = 0; $i < count($u); $i++)
indicates that $u is an array -- and not a single name.
And $i is used to keep track of the current index in that array.
So, in your loop, you should be working with $u[$i] -- which will be the "current" line of the array :
$s = $database->checkUserPlayedRecent($u[$i]);
Note that you could probably rewrite your loop, using a foreach loop, like this :
foreach ($u as $currentPlayer) {
$s = $database->checkUserPlayedRecent($currentPlayer);
// ...
}
With foreach, no need to keep track of the current index -- makes code easier to write and understand, in my opinion ;-)
You should get in the habit of keeping count() outside of your conditional. You're count()ing the same array every time which is a waste of cycles.
$total = count($u);
for ($i=o; $i < $total; $i++) ...
I would definitely query these users all at once, especially since your query is abusing mysql_num_rows when you should be using the following sql:
select username, count(username) from user where username IN (your,array,of,usernames) group by username;
then your foreach loop would iterate over the results and you could reference each row without having to call yet another mysql_* method.
I'd be tempted to rewrite the query to accept the array of names and use an IN statement, so that you could execute the whole of your database activity in a single query rather than once for every entry in the array. It would almost certainly be faster.
If you show us the query that you're using in your checkUserPlayedRecent() method, we may be able to help with this.

Categories