I have multiple fields on admin panel user can add field and delete the fields as well while adding it I placed simple insert query with foreach loop but it is difficult to understand the concept for updating that fields if user deletes a field or updates it is not working if I delete 1 field and update it it deletes 2 or more then 2 fields and when I try to update it is not updating well update issue is due i would be making some mistake with query. But main thing is about logic which I am unable to build it properly need help.
Update query
$video_link = $_POST['video_link'];
$old_links = count($video_link);
if(isset($_POST['video_id'])) {
$video_id = $_POST['video_id'];
$total_id = count($video_id);
} else {
$video_id = '';
}
$video_links = mysqli_query($connect, "SELECT * FROM video_slides WHERE model_id = '$model_id'");
$total_links = mysqli_num_rows($video_links);
$video_link = sizeof($video_link) - 1;
if($total_links >= 1) {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
$query2 = mysqli_query($connect, "UPDATE `video_slides` SET `embeded_link`='$video_link[$i]' WHERE id='$video_id[$i]'");
if($video_link < $total_links) {
$new_total = $total_links-sizeof($video_link);
for($j = 0; $j<=$new_total; $j++) {
mysqli_query($connect, "DELETE FROM video_slides WHERE id='$video_id[$j]'");
}
}
}
} else {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
}
}
And here is my form fields
<div class="form-group">
<label>Video Slides <input type="button" class="add_field_button btn blue" value="Add Field" /></label>
<div class="input_fields_wrap">
<?php
$sql3 = mysqli_query($connection, "SELECT * FROM video_slides WHERE model_id = '".$data['id']."'");
if(mysqli_num_rows($sql3) == 0) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" />
</div>
<?php
} else {
while($video = mysqli_fetch_assoc($sql3)) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" value="<?php echo $video['embeded_link']; ?>" />
<input type="hidden" value="<?php echo $video['id']; ?>" name="video_id[]" />
<a class="remove_field"><i class="fa fa-times"></i></a>
</div>
<?php } } ?>
</div>
</div>
As per my understanding you need only these thing why you making complex coding
$video_link = $_POST['video_link'];
//First Remove All ID
mysqli_query($connect, "DELETE FROM video_slides WHERE model_id='$model_id'");
//Then After insert updated data
foreach($video_link as $key=>$val){
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link`, `model_id`) VALUES ('$val', '$model_id')");
}
you should try to outsource your db connections in a separate class - this will lead to better readable code. An ORM like Doctrine can definitely help you to better understand your own code.
Related
I have tried to write a code that update category in the database using admin panel but whenever i try to do that it won't work and i don't get any errors to look into it, please help guys; thanks a lot
PHP Code:
<?php
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE category_id = $edit_id ";
$edit_get_result = mysqli_query($connection,$query);
if (!$edit_get_result) {
die("Edit Get Result Query FAILED");
}
while ($category_name_row=mysqli_fetch_assoc($edit_get_result)) {
$category_name = $category_name_row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
}
?>
Please check below code. You need to pass edit_id in your form POST. I have put it in a hidden input and set it's value according to the GET parameter from top of your php part.
<?php
if (isset($_GET['edit'])) {
$edit_id = mysqli_real_escape_string($connection,$_GET['edit']);
$query = "SELECT * FROM categories WHERE category_id = '$edit_id' ";
$result = mysqli_query($connection,$query);
if(!$result) {
die("Edit Get Result Query FAILED");
}
while ($row=mysqli_fetch_assoc($result)) {
$category_name = $row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<input type="hidden" name="edit_id" value="<?php if(isset($edit_id)) echo $edit_id;?>">
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit']) && isset($_POST['edit_id'])) {
$category_name = mysqli_real_escape_string($connection,$_POST['update_category']);
$edit_id = mysqli_real_escape_string($connection,$_POST['edit_id']);
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$result = mysqli_query($connection,$query);
if (!$result) {
die("Final Update Query Result FAILED");
}
else echo "Final Update Query Result Success";
}
?>
Hi have noticed that you have used raw inputs. try avoiding it. Also noticed your code had extra curly braces at the end.
Please try using the following code after replacing your end page section php script.
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
And Change your query variable to the following:
$query = "SELECT * FROM categories WHERE category_id = ".$edit_id;
I've searched around and haven't found anything similar, but it sounds like it should be pretty easy...
I have a search query that searches for a specific userID and displays that information for that user. However, I have one field (let's call it "favorite color" for this example) that will need to be manually updated frequently. So, I want to Search by userID, display the results, somehow re-use the original userID, and update the "favorite color" by the user entry. The part I can't figure out yet is how to store/re-use the userID.
The only way I can get it to work is ->
Search for userID, display results and also populate two new text form fields with original userID as well as "favorite color" to be submitted again by a new UPDATE query. But I don't want the userID to be a text form field, I just want to store the variable use it again.
Does that make sense? =)
Here is a sample of my current code. BTW, it works 100% this way right now, just need to figure out how to store the variable instead of using it again in a text box where I submit the UPDATE query.
<div class="searchBox">
<form method="POST" name="search" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="querySearch" placeholder="User ID" required>
<button type="submit">Search</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['querySearch'])){
$query = $_POST['querySearch'];
$min_length = 8;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM sites WHERE userID = $query";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
if(mysqli_num_rows($raw_results) > 0){
while ($results = mysqli_fetch_array($raw_results)) {
echo "<div class='title'>User ID:</div><div class='info'>".$results['userID']."</div>";
echo "<div class='title'>Name:</div><div class='info'>".$results['name']."</div>";
echo "<div class='title'>Fav Color:</div><div class='info'>".$results['favColor']."</div>";
$userID = $results['userID'];
}
}
else { // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
<div class="searchBox">
<form method="POST" name="filterUpdate" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="UserID" value="<?php echo $userID;?>" required><br><br><br>
<input type="text" name="favColor" placeholder="New favColor here..." required>
<button type="submit">Update</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['filterUpdate'])){
$queryFilter = $_POST['filterUpdate'];
$userID = $_POST['userID'];
$min_length = 1;
if(strlen($queryFilter) >= $min_length){
$queryFilter = htmlspecialchars($queryFilter);
$userID = htmlspecialchars($userID);
$queryFilter = mysqli_real_escape_string($conn, $queryFilter);
$userID = mysqli_real_escape_string($conn, $userID);
$sql = "UPDATE sites SET favColor = '$queryFilter' WHERE userID = '$userID'";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
You can try either of this:
Hidden Field:
<input type="hidden" name="UserID" value="<?php echo $userID;?>">
Session:
$_SESSION['userID'] = $userID;
Don't know if this will work, but you can put the $userID above all the codes(like a global var).
This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.
I am trying to create a room availability check page for a hostel and I am having an issue.
I have a database with a table named 'rooms' listing all type of rooms with these rows:
id [INT]
name (room type) [CHAR]
capacity (max capacity, not to be changed)[INT]
used (number of beds used, I want to change this dynamically!) [INT]
I created a code to generate the rooms list from the DB with PHP and I want the "+" and "-" buttons to either add or remove one unit in the used column for a specific room. How can I do this?
Here is my code:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
If you set the action of your form to whatever the name of your code is (e.g., "rooms.php"), then move
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
up to the top so it updates the table before you query the table to fill in the rest of the page, it should work. Right now, your php is updating the table after the SELECT query to populate your page, so it doesn't appear to be updating.
I think a better tack would be implementing AJAX so your form updates the Used field without reloading the page.
Alright so I figured out a way on my own in the end so I post it here for other people facing a similar issue to overcome it ;)
Here is the concerned part of the code in index.php:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
And the code of update.php:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}
I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.