Saving data in mysql using dynamic field names [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have mysql table storing company id, opening/closing hours for days of week and status (closed/open). Made form with fields and updating function. It looks like this. Works, but i believe it can be optimised. Can you suggest how?
FORM:
<form role="form" method="post" action="" autocomplete="off">
<div class="box-body">
<div class="row">
<div class="col-sm-3 text-bold"><div class="padd bg-gray-light">Day</div></div>
<div class="col-sm-3 text-bold"><div class="padd bg-gray-light">Status</div></div>
<div class="col-sm-3 text-bold"><div class="padd bg-gray-light">Opening</div></div>
<div class="col-sm-3 text-bold"><div class="padd bg-gray-light">Closing</div></div>
</div>
<?php while ($h = dbarray($get_hours)) { ?>
<input type="text" name="day" value="<?php echo $h['day_day']; ?>">
<?php
// FORM VALUES
if ($h['day_status'] == 1) {
$status_o = "checked";
$status_c = "";
}
if ($h['day_status'] == 0) {
$status_o = "";
$status_c = "checked";
}
?>
<div class="row">
<div class="col-sm-3">
<h4><?php echo $l['day_'.$h[day_day]]; ?></h4>
</div>
<div class="col-sm-3">
<div class="input-group">
<div class="checkbox">
<label><input type="radio" name="status_<?php echo $h['day_day']; ?>" value="1" <?php echo $status_o; ?>> Dirbame</label>
<label><input type="radio" name="status_<?php echo $h['day_day']; ?>" value="0" <?php echo $status_c; ?>> Uždaryta</label>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<input type="text" name="open_<?php echo $h['day_day']; ?>" class="form-control <?php if ($h['day_status'] == 0) { echo "bg-gray"; } ?>" value="<?php echo $h['day_open']; ?>">
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<input type="text" name="close_<?php echo $h['day_day']; ?>" class="form-control <?php if ($h['day_status'] == 0) { echo "bg-gray"; } ?>" value="<?php echo $h['day_close']; ?>">
</div>
</div>
</div>
<hr style="margin: 3px 0;">
<?php } ?>
</div>
<div class="box-footer">
<button type="submit" name="save" class="btn btn-success pull-right">Save</button>
</div>
</form>
UPDATING PHP:
<?php
if (isset($_POST['save'])) {
// VALUES
$mon_status = stripinput(descript($_POST['status_1'])); $mon_open = stripinput(descript($_POST['open_1'])); $mon_close = stripinput(descript($_POST['close_1']));
$tue_status = stripinput(descript($_POST['status_2'])); $tue_open = stripinput(descript($_POST['open_2'])); $tue_close = stripinput(descript($_POST['close_2']));
$wed_status = stripinput(descript($_POST['status_3'])); $wed_open = stripinput(descript($_POST['open_3'])); $wed_close = stripinput(descript($_POST['close_3']));
$thu_status = stripinput(descript($_POST['status_4'])); $thu_open = stripinput(descript($_POST['open_4'])); $thu_close = stripinput(descript($_POST['close_4']));
$fri_status = stripinput(descript($_POST['status_5'])); $fri_open = stripinput(descript($_POST['open_5'])); $fri_close = stripinput(descript($_POST['close_5']));
$sat_status = stripinput(descript($_POST['status_6'])); $sat_open = stripinput(descript($_POST['open_6'])); $sat_close = stripinput(descript($_POST['close_6']));
$sun_status = stripinput(descript($_POST['status_7'])); $sun_open = stripinput(descript($_POST['open_7'])); $sun_close = stripinput(descript($_POST['close_7']));
// UPDATE
$result1 = dbquery("UPDATE a_days SET day_status='".$mon_status."', day_open='".$mon_open."', day_close='".$mon_close."' WHERE day_day=1");
$result2 = dbquery("UPDATE a_days SET day_status='".$tue_status."', day_open='".$tue_open."', day_close='".$tue_close."' WHERE day_day=2");
$result3 = dbquery("UPDATE a_days SET day_status='".$wed_status."', day_open='".$wed_open."', day_close='".$wed_close."' WHERE day_day=3");
$result4 = dbquery("UPDATE a_days SET day_status='".$thu_status."', day_open='".$thu_open."', day_close='".$thu_close."' WHERE day_day=4");
$result5 = dbquery("UPDATE a_days SET day_status='".$fri_status."', day_open='".$fri_open."', day_close='".$fri_close."' WHERE day_day=5");
$result6 = dbquery("UPDATE a_days SET day_status='".$sat_status."', day_open='".$sat_open."', day_close='".$sat_close."' WHERE day_day=6");
$result7 = dbquery("UPDATE a_days SET day_status='".$sun_status."', day_open='".$sun_open."', day_close='".$sun_close."' WHERE day_day=7");
}
?>

Loop over the numeric suffixes of the field names.
$results = array();
foreach (range(1, 7) AS $daynum) {
$status = stripinput(descript($_POST['status_' . $daynum]));
$open = stripinput(descript($_POST['open_' . $daynum]));
$close = stripinput(descript($_POST['close_' . $daynum]));
$results[$daynum] = dbquery("UPDATE a_days SET day_status='".$status."', day_open='".$open."', day_close='".$close."' WHERE day_day='.$daynum);
}

Related

All the checkboxes checked by previous user must be disabled

I want all the records(i.e seats selected by the user) should be disabled but this code only fetches the last record and disables it.
<?php
$sqlcheck = "select * from booknow where hotel ='$test'";
$resultcheck = mysqli_query($conn,$sqlcheck);
while($rowcheck = mysqli_fetch_array($resultcheck))
{
$checkedcheck = $rowcheck['book'];
$expcheck=explode(",",$checkedcheck);
}
?>
<?php $i=1;
while ($i<=$tab)
{?>
<div class="TWO">
<div class="check"style="height:40px;width:120px;">
<div class="seconda">
</div>
<div class="secondb">
<input type ="checkbox"name="checky[]"class="tabtwo"style="width:30px;height:30px;"
value="<?php echo "Two-seater A".$i;?>"
<?php if(in_array("Two-seater A".$i, $expcheck)) {?>
onclick="this.checked=this.defaultChecked"<?php } else {echo "none";}?>>
</div>
<div class="secondc">
</div>
<label for="c1"style="margin-left:40px;"><b>A<?php echo$i?></b>
</label>
</div>
</div>
<?php
$i++;
}
?>
Try below code
while($rowcheck = mysqli_fetch_array($resultcheck))
{
$checkedcheck = $rowcheck['book'];
$expcheck[] =explode(",",$checkedcheck);
}

PHP Insert data in database from array and output db data in html table

I'm having a problem with inserting data in my MySQL db table from an array. I have a form and an array which stores submitted values and its contents I display in a html table. In each table row there are values from one submit and a button which deletes the row with jQuery.
The problem is I also need the functionality to select a row from the html table and insert in my database table. I would like a button on each row's end that when clicked would insert the rows contents in my database table, similar to what i have now with deleting a row from my html table.
Deleting can be done with simple jQuery, but with this I have no idea how to continue, thanks for answers in advance.
This is how far i have gotten:
<div class="row">
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> ";
echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
</script>
You might want something like this
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
// insert all inputs to an a new array
$newInfo = array($_POST['code'], $_POST['title'], $_POST['number'], $_POST['value'], $_POST['retailvalue']);
// push the new array to session variable 'info'
array_push($_SESSION['info'], $newInfo);
// as you already have, loop thru each session info
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr><td></td>";
// echo each value to table cells
foreach($_SESSION['info'][$i] as $value){
echo "<td>".$value."</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\"></i>Delete</a></td> ";
echo "</tr>";
}
}
Plus the condition for checking error on retail value is wrong if you want it to be smaller than inventory value. Please double check
I decided to use Ajax to post the data to Database.
You could see that I used javascript method called postToDatabase to post the data and the data has been passed as arguments to the method.
Check out the code below.
<?php
// your database connection and database selection using PDO ( Safe and better to use PDO)
//BEGINNING OF DATABASE CONNECTION
$servername = "localhost";
$username = "root";
$password = "password";
$db_name = "db";
$db_engine = 'mysql';
try {
$conn = new PDO("$db_engine:host=$servername;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{ echo "Connection failed: " . $e->getMessage(); }
// END OF DATABSE CONNECTION
//DATA POSTED VIA AJAX
$code = trim($_POST["code"]);
$title = trim($_POST["title"]);
$number = trim($_POST["number"]);
$value = trim($_POST["value"]);
$retailValue = trim($_POST["retailvalue"]);
// BEGINNING OF INSERT QUERY
$sql = $conn ->prepare("INSERT INTO books (code, title, number, value, retailvalue) VALUES (?, ?, ?, ?, ?)"); // ? WILL BE REPLACED BY THEIR RESPECTIVE VALUES IN THE EXEC() METHOD.
$sql->execute(array($code, $title, $number, $value, $retailValue));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div id="success_msg" class="alert alert-success fade in" style="display:none;">
×
<strong>Success!</strong> Data Saved.
</div>
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<form name="form">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
$vals .= "'$key',";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> "; ?>
<td>
<a onclick="postToDatabase(<?php echo substr($vals,0,-1); $vals=NULL; ?>);" class="add" href="#"> <i class="fa fa-plus" aria-hidden="true"></i>
</a>
</td>
<?php echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</form>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
</div>
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
function postToDatabase(code, title,number,value,retailvalue){
$.ajax({
type: "POST",
url: 'index.php',
data: "code=" + code + "&title=" + title + "&number=" + number + "&value=" + value + "&retailvalue=" + retailvalue,
success: function (msg) {
$('#success_msg').show();
}
});
}
</script>
</body>
</html>

There's no error, but its not working about UPDATE query in PHP and MySQL [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I don't what is the wrong about this, there's no error but its not working about the update query. I don't know if its the latest code or old code. The first code is the accommodation_server.php.
Here's the structure:
<?php
session_start();
$title_room = "";
$room_size = "";
$occupancy = "";
$bed = "";
$rate = "";
$others = "";
$others1 = "";
$others2 = "";
$others3 = "";
$others4 = "";
$id = 0;
$edit_state = false;
//connect to the database
$db = mysqli_connect('localhost', 'root', '', 'accommodation');
//update
if (isset($_POST['update'])) {
$title_room = $_POST['text_title'];
$room_size = $_POST['text_size'];
$occupancy = $_POST['text_occupancy'];
$rate = $_POST['text_rate'];
$others = $_POST['text_others1'];
$others1 = $_POST['text_others2'];
$others2 = $_POST['text_others3'];
$others3 = $_POST['text_others4'];
$others4 = $_POST['text_others5'];
$bed = $_POST['text_bed'];
$description = $_POST['text_description'];
$id = $_POST['text_id'];
mysqli_query($db, "UPDATE rooms SET title_room = '$title_room', room_size = '$room_size', occupancy = '$occupancy', rate = '$rate', bed = '$bed', others = '$others', others1 = 'others1', others2 = '$others2', others3 = '$others3', others4 = '$others4', description = '$description' where id=$id");
$_SESSION['msg'] = "Room Updated!";
header('location: accommodation.php');
}
//retrieve records
$results = mysqli_query($db, "SELECT * FROM rooms");
?>
and this is the accommodation.php
<?php include ('accomodation_server.php');
//fetch the record
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$edit_state = true;
$rec = mysqli_query($db, "SELECT * FROM rooms where id=$id");
$record = mysqli_fetch_array($rec);
$title_room = $record['title_room'];
$room_size = $record['room_size'];
$occupancy = $record['occupancy'];
$rate = $record['rate'];
$others = $record['others'];
$others1 =$record['others1'];
$others2 = $record['others2'];
$others3 = $record['others3'];
$others4 = $record['others4'];
$bed = $record['Bed'];
$description = $record['description'];
$id = $record['id'];
}
?>
<html>
<head>
<title>C M S</title>
<link rel="stylesheet" type="text/css" href="css/accommodation.css">
<meta name="viewport" content="width=device-width, initial-scale: 1.0, user-scalable=0"/>
</head>
<body>
<?php if(isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
</div>
<?php endif ?>
<div id="container">
<div class="sidebar">
<ul id="nav">
<li>Dashboard</li>
<li><a class="selected" href="cms.php">CMS</a></li>
<li>Account Settings</li>
<li>Logout</li>
</ul>
</div>
<div class="content">
<br>
<br>
<h1>Accommodation</h1>
<p>Edit and remove images or description.</p>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<form method="post" action="#">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div id="box">
<div class="title-room"><b> <!--title ng room--> <?php echo $row['title_room']; ?></b></a>
Edit
<input type="text" name="text_title" placeholder = "Enter the name of the room..." class="title" value="<?php echo $title_room; ?>">
</div>
<div class="box-top">Room Size:<p><?php echo $row['room_size']; ?></p></a>
<input type="text" name="text_size" placeholder = "Enter the size of the room..." class="size" value="<?php echo $room_size; ?>">
</div>
<div class="box-top">Bed: <p><?php echo $row['Bed']; ?></p></a>
<input type="text" name="text_bed" placeholder = "Enter the bedtype of the room..." class="bed" value="<?php echo $bed; ?>">
</div>
<div class="box-top">Occupancy: <p><?php echo $row['occupancy']; ?></p></a>
<input type="text" name="text_occupancy" placeholder = "Enter the occupancy of the room..." class="occupancy" value="<?php echo $occupancy; ?>">
</div>
<div class="box-top">Rate from: <p><?php echo $row['rate']; ?></p></a>
<input type="text" name="text_rate" placeholder = "Enter the rate of the room..." class="rate" value="<?php echo $rate; ?>">
</div>
<div class="box-top">Others:
<p class="others1"> <br>
<input type="text" name="text_others1" placeholder = "Others..." class="t_others1" value="<?php echo $others; ?>">
<?php echo $row['others']; ?></p> <br>
<p class="others2">
<input type="text" name="text_others2" placeholder = "Others..." class="t_others2" value="<?php echo $others1; ?>">
<?php echo $row['others1']; ?></p> <br>
<p class="others3">
<input type="text" name="text_others3" placeholder = "Others..." class="t_others3" value="<?php echo $others2; ?>">
<?php echo $row['others2']; ?></p><br>
<p class="others4">
<input type="text" name="text_others4" placeholder = "Others..." class="t_others4" value="<?php echo $others3; ?>">
<?php echo $row['others3']; ?></p> <br>
<p class="others5">
<input type="text" name="text_others5" placeholder = "Others..." class="t_others5" value="<?php echo $others4; ?>">
<?php echo $row['others4']; ?></p></a><br> </div>
<div class="box-panel">
<?php echo $row['description']; ?>
<br><p> </p>
<textarea placeholder = "Enter the Description of the Room..." rows="4" cols="100" class="description" name="text_description" value="<?php echo $description; ?>">
</textarea>
</div>
<?php if ($edit_state == false): ?>
<button type="submit" name="edit_button" class="edit_button">Edit</button>
<?php else: ?>
<button type="submit" name="update" class="btn">Update</button>
<?php endif ?>
</form>
<?php } ?>
<div id="box">
<div class="box-top">Destination</div>
<div class="box-panel">
Information of the resort (contact number, destination, etc)
</div>
<div id="box">
<div class="box-top">Accommodation</div>
<div class="box-panel">
Rooms, and the description of the room.
</div>
<div id="box">
<div class="box-top">Photos</div>
<div class="box-panel">
All images of the website.
</div>
</div>
</div>
</div>
<div id="header">
<div class="logo">Pacific Sky Beach Resort Admin Panel <span></span></div>
</div>
</body>
</html>
mysqli_query($db, "UPDATE rooms SET title_room = '$title_room', room_size = '$room_size', occupancy = '$occupancy', rate = '$rate', bed = '$bed', others = '$others', others1 = 'others1', others2 = '$others2', others3 = '$others3', others4 = '$others4', description = '$description' where id='$id'");
you missed the '' surrounding id='$id' in the first code sample
and again in the second
$rec = mysqli_query($db, "SELECT * FROM rooms where id='$id'");
also if you add print_r($db) after your query's it will show you if there are any errors in your sql request

PHP mysqli while loop called twice

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
}

How to loop or foreach it

I cannot foreach loop my comment & reply system. I read many article and example but can't apply these in my case.
This is my comment system with reply, here every think is working well. But reply form work for only last/new comment. So i need to loop each comment. But can't do, please help me.
global $dbh;
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 5") or die(mysqli_error($dbh));
echo'<div class="comments"><div id="updates"><div class="content"><comment>';
// Show only main comment
while($row = mysqli_fetch_array($results))
{ $id = $row['id'];
$qazi_id = $row['qazi_id'];
$username = $row['username'];
$description = $row['description'];
$parent_id = $row['parent_id'];
$date = $row['date'];
//echo comment
echo'<div class="comment">
<div class="cdomment_cheder">';
echo'<p>'.$username.' Says:</p>';
echo'<span>'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div></div></div>
<div class="cdomment_text">';
if ($description=="") {echo '';}
else echo''.htmlentities($description).'<br>';
echo '</div>';
//reply
echo'<div class="reply_box">Reply</div>';
//Reply form
echo'<div id="loader"></div><div class="reply_here" id="reply_here-'.$id.'" style="display:none;">
<form action="" method="post" id="repfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<input type="hidden" name="username" tabindex="1" id="author" value="'.$username.'"/>
<textarea name="replycom" rows="2" tabindex="4" id="replycom" value=""></textarea>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
<button type="submit" name="submit" value="" tabindex="5" id="submit" class="repfrm">Post Reply</button>
</fieldset>
</form>
</div>';
// Show Reply of each comment
$query = "SELECT * FROM comments_reply WHERE parent_id ='".$id."'";
$res = mysqli_query($dbh,$query);
while($row = mysqli_fetch_array($res))
{ $id = $row['id'];
$qazi_id = $row['qazi_id'];
$username = $row['username'];
$description = $row['description'];
$parent_id = $row['parent_id'];
$date = $row['date'];
//echo reply
echo' <div class="rcontent"><replycomment><ul>
<div class="comment">
<div class="cdomment_cheder">';
echo'<p class="name">'.$username.' Says:</p>';
echo'<span>'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div></div></div>
<div class="cdomment_text">';
if ($description=="") {echo '';}
else echo''.htmlentities($description).'<br>';
echo '</div>';
echo'</ul><replycomment></div>';
} //reply while close
} //comment while close
echo'</div><comment></div>';

Categories