I have this code:
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
while($langs = mysqli_fetch_assoc($r)){
$l_id = $langs['id'];
$l_name = $langs['name_en'];
?>
<li <?php if($l_id == '1'){ echo 'class="active"'; }?>><?php echo $l_name;?></li>
<?php } // closing 1st while loop
?>
</ul>
<div class="tab-content">
<?php
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
while($langs = mysqli_fetch_assoc($r)){
$l_id = $langs['id'];
$l_lang = $langs['language'];
$l_name = $langs['name_en'];
?>
<div class="tab-pane fade <?php if($l_id == '1'){ echo 'in active'; }?>" id="<?php echo $l_name;?>">
<div class="form-group col-xs-4">
<label for="title_<?php echo $l_lang;?>">Title:</label>
<input class="form-control" type="text" name="title_<?php echo $l_lang;?>" id="title_<?php echo $l_lang;?>" value="<?php echo $opened['title_'.$l_lang.'']; ?>" placeholder="Page Title">
</div>
<div class="form-group col-xs-4">
<label for="header_<?php echo $l_lang;?>">Header:</label>
<input class="form-control" type="text" name="header_<?php echo $l_lang;?>" id="header_<?php echo $l_lang;?>" value="<?php echo $opened['header_'.$l_lang.'']; ?>" placeholder="Page Header">
</div>
<div class="form-group col-xs-<?php if($page_type == 'tour'){ echo 8;}else {echo 12;} ?>">
<label for="body_<?php echo $l_lang;?>">Body:</label>
<textarea class="form-control editor" name="body_<?php echo $l_lang;?>" id="body_<?php echo $l_lang;?>" rows="7" placeholder="Page Body"><?php echo $opened['body_'.$l_lang.'']; ?></textarea>
</div>
</div>
<?php } //closing 2nd while loop
?>
</div>
When running it, the result is a tabbed form (I skipped the form tags and some html from above, to reduce the code writen) and everything is OK.
My questions are:
How to have the same output, but with a single query and while loop?
Is it possible to make this a function? Any hints?
Thank you!
I think you will have to loop twice, but you don't need to make two queries at all!
Use mysqli_fetch_all to store the results in an array and then loop through it
For example:
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
$langs = mysqli_fetch_all($r);
foreach($langs as $lang){
//render links
}
//...
foreach($langs as $lang){
//render tabs
}
Your script will run much faster
Try
<?php
function get_rows()
{
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
$languages = array();
while($langs = mysqli_fetch_assoc($r))
{
$languages[] = $langs;
}
return $languages;
}
$languages = get_rows();
if($languages != false)
{
?>
<ul>
<?php
foreach($languages as $langs)
{
$l_id = $langs['id'];
$l_name = $langs['name_en'];
?>
<li <?php
if($l_id == '1')
{
echo 'class="active"';
}
?>><?php echo $l_name; ?></li>
<?php
}
?>
</ul>
<div class="tab-content">
<?php
foreach($languages as $langs)
{
$l_id = $langs['id'];
$l_lang = $langs['language'];
$l_name = $langs['name_en'];
?>
<div class="tab-pane fade <?php
if($l_id == '1')
{
echo 'in active';
}
?>" id="<?php echo $l_name; ?>">
<div class="form-group col-xs-4">
<label for="title_<?php echo $l_lang; ?>">Title:</label>
<input class="form-control" type="text" name="title_<?php echo $l_lang; ?>" id="title_<?php echo $l_lang; ?>" value="<?php echo $opened['title_' . $l_lang . '']; ?>" placeholder="Page Title">
</div>
<div class="form-group col-xs-4">
<label for="header_<?php echo $l_lang; ?>">Header:</label>
<input class="form-control" type="text" name="header_<?php echo $l_lang; ?>" id="header_<?php echo $l_lang; ?>" value="<?php echo $opened['header_' . $l_lang . '']; ?>" placeholder="Page Header">
</div>
<div class="form-group col-xs-<?php
if($page_type == 'tour')
{
echo 8;
}
else
{
echo 12;
}
?>">
<label for="body_<?php echo $l_lang; ?>">Body:</label>
<textarea class="form-control editor" name="body_<?php echo $l_lang; ?>" id="body_<?php echo $l_lang; ?>" rows="7" placeholder="Page Body"><?php echo $opened['body_' . $l_lang . '']; ?></textarea>
</div>
</div>
<?php } ?>
</div>
<?php
}
?>
Save results while first iterating in some array and the iterate over this array for the second time:
$tmp_array = array();
while ($langs = mysqli_fetch_assoc($r)){
$tmp_array[] = $langs;
}
//some code here
//and second array
foreach ($tmp_array as $langs) {
//more code here
}
Related
I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>
How do make my search work from a class... i can display my search results on the major page but i want it to display all results and if it is more than the paginated result, client can easily move to another page.
<?php
// if it's going to need the database, then it's
//probably smart to require it before we start.
#require_once(LIB_PATH.DS.'database.php');
class Product extends DatabaseObject {
protected static $table_name="products";
protected static $db_fields=array('id', 'product_id', 'image', 'title', 'slug', 'description', 'price');
public $id;
public $product_id;
public $image;
public $title;
public $slug;
public $description;
public $price;
public static function search(){
global $database;
$sql = "SELECT * FROM products WHERE image LIKE '{%$search%'";
$sql .= " OR title LIKE '{%$search%}'";
$sql .= " OR slug LIKE '%$search%'";
$sql .= " OR description LIKE '%$search%'";
$sql .= " OR price LIKE '%$search%'";
$total_count = count($sql);
$result_set = $database->query($total_count);
$row = $database->fetch_assoc($result_set);
return array_shift($row);
}
?>
Please check my code... i am a bit confused.
<?php if(empty($_POST['search'])){
$session->message("<div class='error-msg'>Search cannot be empty</div>");
redirect_to('photos.php');
}
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<?php
if(isset($_POST['submit'])){
// 1. the current page number ($current_page)
$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
// 2. records per page ($per_page)
$per_page = 10;
// 3. total record count ($total_count)
//$total_count = Product::count_all();
$total_count = Product::search();
// Find all photos
// use pagination instead
$pagination = new Pagination($page, $per_page, $total_count);
// Instead of finding all records, just find the records
$search = $database->escape_value($_POST['search']);
// $sql = "SELECT * FROM products WHERE image LIKE '%$search%'";
// $sql .= " OR title LIKE '%$search%'";
// $sql .= " OR slug LIKE '%$search%'";
// $sql .= " OR description LIKE '%$search%'";
// $sql .= " OR price LIKE '%$search%'";
// $sql .= " LIMIT {$per_page} ";
// $sql .= "OFFSET {$pagination->offset()}";
$search = new Product();
$search->search = $search;
$photos = Product::find_by_sql($search);
//$total_count = count($photos);
//echo $numresults = '<p class="error-msg">There are '.$total_count.' results in your search</p><br/><br/>';
foreach ($photos as $photo): ?>
<div class="col-md-4 col-sm-6">
<div class="row">
<div id="pagination" style="clear: both;">
<nav aria-label="Page navigation example">
<ul class="pagination">
<?php
for($i=1; $i <= $pagination->total_pages(); $i++){
if($i == $page) {
// echo " <span class=\"selected\">{$i}</span> ";
// } else{
// echo " {$i} ";
}
}
if($pagination->total_pages() > 1) {
if($pagination->has_previous_page()) {
echo "<li class='page-item'><a class='page-link' href=\"search.php?page=";
echo $pagination->previous_page();
echo "\">« Previous</a></li> ";
}
if($pagination->has_next_page()){
echo "<li class='page-item'><a class='page-link' href=\"search.php?page=";
echo $pagination->next_page();
echo "\">Next »</a></li>";
}
}
?>
</ul>
</nav>
</div>
</div>
<div class="thumbnail">
<form method="post" action="cart.php?action=add&id=<?php echo $photo->id; ?>" role="form" class="form-vertical">
<a href="order_review.php?id=<?php echo $photo->id; ?>"><img src="<?php echo $photo->image_path();
?>" class="img-thumbnail" alt="responsive image"></a>
<div class="caption">
<h3 class="text-info text-center"><?php echo $photo->title; ?></h3>
<p class="text-muted text-center price card-header"><span class="currency">N</span><?php echo $photo->price; ?></p>
<p class="text-center"><em><?php echo $photo->description; ?></em></p>
<input type="hidden" name="id" class="form-control" value="<?php echo $photo->id; ?>" />
<input type="hidden" name="title" class="form-control" value="<?php echo $photo->title; ?>" />
<input type="hidden" name="slug" class="form-control" value="<?php echo $photo->slug; ?>" />
<input type="hidden" name="description" class="form-control" value="<?php echo $photo->description; ?>" />
<input type="hidden" name="price" class="form-control" value="<?php echo $photo->price; ?>"/>
<div class="col-sm-4 mx-auto d-block">
<select name="quantity" class="form-control" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<div class="col-sm-4 col-sm-push-3 mx-auto d-block">
<input type="submit" name="add_to_cart" class="btn bg-success" value="Add to cart" />
</div><br/>
</form>
</div>
</div>
<?php endforeach; }
?>
</div>
</div>
PLease take note of the code i commented out... I am a bit confused.
Can't make basic things. The connection to database is good, cause it shows list, deletes data lines. Also after submiting, it doesn't show any errors, but it doesn't show in database...I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code
This is my model class:
<?php
class abonimentas {
private $abonimentas_lentele = '';
public function __construct() {
$this->abonimentas_lentele = config::DB_PREFIX . 'abonimentas';
}
public function getAbonimentasListCount() {
$query = " SELECT COUNT(`{$this->abonimentas_lentele}`.`id`) as `kiekis`
FROM `{$this->abonimentas_lentele}`";
$data = mysql::select($query);
return $data[0]['kiekis'];
}
public function getAbonimentas($id) {
$query = " SELECT *
FROM `{$this->abonimentas_lentele}`
WHERE `id`='{$id}'";
$data = mysql::select($query);
return $data[0];
}
public function insertAbonimentas($data) {
$query = " INSERT INTO `abonimentas`
(
`pavadinimas`,
`aprasymas`,
`papildomos_salygos`,
`kaina`
)
VALUES
(
'{$data['pavadinimas']}',
'{$data['aprasymas']}',
'{$data['papildomos_salygos']}'
'{$data['kaina']}'
)";
mysql::query($query);
return mysql::getLastInsertedId();
}
public function updateAbonimentas($data) {
$query = " UPDATE `abonimentas`
SET `pavadinimas`='{$data['pavadinimas']}',
`aprasymas`='{$data['aprasymas']}',
`papildomos_salygos`='{$data['papildomos_salygos']}',
`kaina`='{$data['kaina']}'
WHERE `id`='{$data['id']}'";
mysql::query($query);
}
}
This is creation class:
<?php
include 'libraries/abonimentas.class.php';
$abonimentasObj = new abonimentas();
$formErrors = null;
$data = array();
$required = array('pavadinimas', 'aprasymas', 'papildomos_salygos', 'kaina');
$maxLengths = array (
'pavadinimas' => 40,
'aprasymas' => 200,
'papildomos_salygos' => 200
);
if(!empty($_POST['submit'])) {
// nustatome laukų validatorių tipus
$validations = array (
'pavadinimas' => 'anything',
'aprasymas' => 'anything',
'papildomos_salygos' => 'anything',
'kaina' => 'price');
include 'utils/validator.class.php';
$validator = new validator($validations, $required, $maxLengths);
if($validator->validate($_POST)) {
$dataPrepared = $validator->preparePostFieldsForSQL();
$dataPrepared['id'] = $abonimentasObj->insertAbonimentas($dataPrepared);
$abonimentasObj->updateAbonimentas($dataPrepared);
header("Location: index.php?module={$module}&action=list");
die();
} else {
$formErrors = $validator->getErrorHTML();
$data = $_POST;
}
}
include 'templates/abonimentas_form.tpl.php';
?>
This is template for input:
<ul id="pagePath">
<li>Pradžia</li>
<li>Abonimentai</li>
<li><?php if(!empty($id)) echo "Abonimento redagavimas"; else echo "Naujas abonimentas"; ?></li>
</ul>
<div class="float-clear"></div>
<div id="formContainer">
<?php if($formErrors != null) { ?>
<div class="errorBox">
Neįvesti arba neteisingai įvesti šie laukai:
<?php
echo $formErrors;
?>
</div>
<?php } ?>
<form action="" method="post">
<fieldset>
<legend>Abonimento informacija</legend>
<p>
<label class="field" for="pavadinimas">Pavadinimas<?php echo in_array('pavadinimas', $required) ? '<span> *</span>' : ''; ?></label>
<input type="text" id="pavadinimas" name="pavadinimas" class="textbox textbox-200" value="<?php echo isset($data['pavadinimas']) ? $data['pavadinimas'] : ''; ?>">
<?php if(key_exists('pavadinimas', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['pavadinimas']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="aprasymas">Aprašymas<?php echo in_array('aprasymas', $required) ? '<span> *</span>' : ''; ?></label>
<textarea id="aprasymas" name="aprasymas" class=""><?php echo isset($data['aprasymas']) ? $data['aprasymas'] : ''; ?></textarea>
<?php if(key_exists('aprasymas', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['aprasymas']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="papildomos_salygos">Papildomos sąlygos<?php echo in_array('papildomos_salygos', $required) ? '<span> *</span>' : ''; ?></label>
<textarea id="papildomos_salygos" name="papildomos_salygos" class=""><?php echo isset($data['papildomos_salygos']) ? $data['papildomos_salygos'] : ''; ?></textarea>
<?php if(key_exists('papildomos_salygos', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['papildomos_salygos']} simb.)</span>"; ?>
</p>
<p>
<label class="field" for="kaina">Kaina<?php echo in_array('kaina', $required) ? '<span> *</span>' : ''; ?></label>
<input type="number" id="kaina" name="kaina" class=""><?php echo isset($data['kaina']) ? $data['kaina'] : ''; ?></input>
<?php if(key_exists('kaina', $maxLengths)) echo "<span class='max-len'>(iki {$maxLengths['kaina']} simb.)</span>"; ?>
</p>
</fieldset>
<p class="required-note">* pažymėtus laukus užpildyti privaloma</p>
<p>
<input type="submit" class="submit button" name="submit" value="Išsaugoti">
</p>
<?php if(isset($data['id'])) { ?>
<input type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
</form>
</div>
code:
<?php
$id = $_GET['id'];
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
}
if(isset($_POST['update']))
{
$admin_id = $_POST['admin_id'];
$chk="";
foreach($admin_id as $chk1)
{
$chk .= $chk1.",";
}
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
}
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admin_id as $admin_id)
{
$chk = "";
if (in_array($chk, $admin_id))
{
$chk = 'checked="checked" ';
}
echo '<input type="checkbox" name="admin_id[]" value="'.$admin_id.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="<?php echo $priority; ?>"><?php echo $priority; ?></option>
<option value="">choose any one</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>
In this code I am fetching multiple checkbox value from table admin2 and I want when I update form value checkbox check if the value of checkbox is exist into database. How can I fix it ?
Thank You
Your code has few issues,
1. Update should be done before select query
2. List of admin not managed separately
3. Priority radio buttons not managed properly
Additional Suggestions,
1. Use prepare query statements
2. use implode for appending multiple values instead of foreach
3. print admin names before checkboxes
<?php
$id = $_GET['id'];
if(isset($_POST['update']))
{
$chk = implode(',', $_POST['admin_id']);
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
$msg = "";
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
echo $msg;
}
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
$admins = array('admin1', 'admin2', 'admin3', 'admin4', 'admin5', 'admin6', 'admin7', 'admin8');
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admins as $admin)
{
$chk = "";
if (in_array($admin, $admin_id))
{
$chk = 'checked="checked" ';
}
echo $admin.' <input type="checkbox" name="admin_id[]" value="'.$admin.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="1" <?php if($priority == 1) echo "selected='selected'"; ?>>1</option>
<option value="0" <?php if($priority == 0) echo "selected='selected'"; ?>>0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>
I'm using a foreach to save in database my form datas.
And, sometimes some values are empty because it's the same as the last value entered. I would like (if the current iteration value is empty) to get the last iteration value and to print it.
Do you have a solution?
Thank you!
<?php
$html = file_get_contents("Intranet link");
function parseTable($html){
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = true;
$tables = $dom->getElementById('tblResultats');
$rows = $tables->getElementsByTagName('tr');
return $rows;
}
$rows = parseTable($html);
$i = 1;
$count = 0;
foreach ($rows as $row){
if($i <> 1 ){
$cols = $row->getElementsByTagName('td');
if (preg_match('/visite/i',$cols->item(0)->nodeValue)) {
$count = $count-1;
}else{
$cols->item(6)->nodeValue = str_replace(' ', '', $cols->item(6)->nodeValue);
$train_nbr = preg_replace("/[^0-9,.]/", "", $cols->item(6)->nodeValue);
if($train_nbr == ""){
$train_nbr = "00000";
}
?>
<div id="criter_<?php echo $count; ?>" class="panel <?php if($cols->item(4)->nodeValue == " -Z"){ echo "panel-z-series"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "panel-x-series"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "panel-bb-series"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "panel-b-series"; } ?>">
<input type="hidden" name="trainid_<?php echo $count; ?>" value="<?php echo $train_nbr; ?>">
<input type="hidden" name="traintype_<?php echo $count; ?>" value="<?php echo $cols->item(4)->nodeValue; ?>">
<input type="hidden" name="userid_<?php echo $count; ?>" value="<?php echo $_SESSION["Auth"]["username"]; ?>">
<input type="hidden" name="entrydate_<?php echo $count; ?>" value="<?php echo date("d/m/Y"); ?> <?php echo $cols->item(2)->nodeValue; ?>">
<input type="hidden" name="leftdate_<?php echo $count; ?>" value="<?php echo $cols->item(8)->nodeValue; ?>">
<input type="hidden" name="openeddate_<?php echo $count; ?>" value="<?php echo date("d/m/Y H:i:s"); ?>">
<input type="hidden" name="entrynumber_<?php echo $count; ?>" value="<?php echo $cols->item(0)->nodeValue; ?>|<?php echo $cols->item(1)->nodeValue; ?>">
<input type="hidden" name="leftnumber_<?php echo $count; ?>" value="<?php echo $cols->item(7)->nodeValue; ?>|<?php echo $cols->item(9)->nodeValue; ?>">
<div class="panel-heading">
<button onclick='addValue();$("#criter_<?php echo $count; ?>").remove();' class="btn btn-default"><i class="fa fa-trash"></i></button>
<strong><?php echo $cols->item(2)->nodeValue; ?> </strong>
<div style="font-size:18px;margin-top:-30px"><?php if($cols->item(4)->nodeValue == " -Z"){ echo "<strong>Z</strong>"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "<strong>X</strong>"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "<strong>BB</strong>"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "<strong>B</strong>"; } echo $train_nbr; ?></div>
<span class="pull-right">
<div class="input-group date picker" >
<input type="text" class="form-control" value="<?php echo $cols->item(8)->nodeValue; ?>"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</span>
<br>
<!-- If values from current iteration are empty, get the values from the -1 iteration -->
Train numéro <strong><?php echo $cols->item(0)->nodeValue; ?></strong> en provenance de <strong><?php echo $cols->item(1)->nodeValue; ?></strong> et à destination de <strong><?php echo $cols->item(9)->nodeValue; ?></strong> (<strong><?php echo $cols->item(7)->nodeValue; ?></strong>)
</div>
<div class="panel-body">
<div id="room_criter_<?php echo $count; ?>">
<p>
Commentaire sur l'engin :<br>
<input type="text" style="width:100%;display: inline-block;margin-bottom:8px;" name="comments_<?php echo $count; ?>" placeholder="Commentaire éventuel sur cet engin (imprévu par exemple)" class="form-control">
Planification des événements :<br>
<input type="text" style="width:70%;display: inline-block;margin-bottom:8px;" name="eventcriter_<?php echo $count; ?>[]" placeholder="Evènement ou intervention planifiée sur cet engin" class="form-control">
<input type="hidden" name="lastmodified_<?php echo $count; ?>[]" value="<?php echo $_SESSION['Auth']['username']; ?>" class="form-control">
<select style="width:19%;display: inline-block;" class="form-control" name="eventcriterstatus_<?php echo $count; ?>[]">
<option value="0" selected>Non effectuée</option>
<option value="1">En cours</option>
<option value="2">Terminée</option>
</select>
<a style="display: inline-block;border-radius: 4px;" class="btn btn-success" onclick="add_fields(<?php echo $count; ?>);"><span class="fa fa-plus"></span> Ajouter</a>
</p>
</div>
</div>
</div>
<?php
}
}
$i++;
$count++;
}
?>
I'm not sure if I understood the task right, but here's my try.
for ($i = 2, $n = count($rows); $i < $n; ++$i) {
$row = $rows[$i - 1];
$prevRow = $rows[$i - 2];
$cols = $row->getElementsByTagName('td');
$prevCols = $prevRow->getElementsByTagName('td');
$values = [];
for ($j = 0; $j < ITEMS_COUNT; ++$j) {
$value = $cols->item($j)->nodeValue;
if (empty($value)) {
$value = $prevCols->item($j)->nodeValue;
}
$values[$j] = $value;
}
//And then you can use $values[$j] instead of $cols->item($j)->nodeValue.
}