I want to update my array into my database with the data from the form. Below is my form:
$query = "SELECT category FROM `$tablename`";
$result2 = mysqli_query($link, $query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
?>
<div class="center_content">
<div id="right_wrap">
<div id="right_content">
<ul id="tabsmenu" class="tabsmenu">
<li class="active">Update Category</li>
<li class="">Add Category</li>
<li class="">View All Category</li>
</ul>
<div id="tab1" class="tabcontent">
<div style="margin:0 auto" align=center>
</div>
<div class="form">
<form action="editCatB.php" method="post">
<div class="form_row">
<label>Outlet Name:</label>
<input type="text" class="form_input" name="tablename" value="<?php echo $name; ?>"readonly/>
</div>
<div class ="form_row">
<label>Outlet Category/Stalls :</label>
</div>
<div class="form_row">
<div class="input_fields_wrap">
<?php
mysqli_data_seek($result2, 0);
while ($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
?>
<div><input class="form_input" type="text" name="mytext[]"value="<?php echo $row2['category']; ?>
"></div>
<?php
}
}
?>
And here is my sql. I want to know how to update the respectively row. Because right now it just update all of my category into the first value
$tableName = $_POST['tablename'];
$values = $_POST['mytext'];
$tableCat = $tableName . "categoryList";
$newString = preg_replace('/\s+/', '', $values);
for ($i = 0; $i < count($newString); $i++) {
$cat = $newString[$i];
$sql = "UPDATE `$tableCat` SET category = `$cat`";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
It also returns me with the error 'Unknown column 'abc' in 'field list'
1) Backticks are for table names and column names, not column values. You'll want to use regular quotes, or take advantage of mysqli's bindings, which is recommended to prevent sql injection.
2) You want to use a WHERE clause when updating. I'd suggest using the id value for the row when creating the table
<div><input class="form_input" type="text" name="mytext[<?php echo $row2['id']?>]" value="<?php echo $row2['category']; ?>"></div>
Then when you iterate through the values, you can pull out the id:
foreach($newString as $id=>$cat) {
$sql = "UPDATE `$tableCat` SET category = '$cat' WHERE id = '$id'";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
}
First,
$sql = "UPDATE `$tableCat` SET category = `$cat`";
Should be more like:
$sql = "UPDATE `$tableCat` SET category = '$cat'";
That being said, you're extremely vulnerable to SQL injection. Look into prepared statements.
If you want to update multiple rows with conditionals, you would follow a pattern similar to this:
$sql = "
UPDATE `$tableCat` SET
category = '$cat',
foo = '$foo',
bar = '$bar'
WHERE baz = '$baz'
";
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 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.
I am trying to do a simple edit/update of my data in the database. But somehow it will not work.
So I am able to read out the saved data into the form. I also don't have any errors
I have stared at my code and googled for hours but I don't see where I might have made a mistake with my code.
The printed echo gives the following output which seems to be right:
HTML code:
<form id="formAddCategory" class="FrmCat" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group">
<!-- hidden id from tbl -->
<input type="hidden" name="hiddenId" value="<?php echo $hiddenID ?>" />
<label for="recipient-name" class="control-label">Category Name:</label>
<input type="text" class="form-control" id="recipient-name1" name="category" required="" value="<?php echo $category ?>" />
</div>
<button type="submit" id="btnEditCat" class="btn btn-danger" name="editCategory">Save Category</button>
</form>
Part of my php code to edit/update:
<?php
//edit/update data to db
if(isset($_POST['editCategory'])){
$categoryUpdate = mysqli_real_escape_string($con, $_POST['category']);
$categoryID = mysqli_real_escape_string($con, $_POST['hiddenId']);
$qry = "UPDATE tbl_Category SET category = $categoryUpdate WHERE category_id = $categoryID";
$result = mysqli_query($con, $qry);
echo $qry;
if($result){
header("Location: category.php");
}
}
?>
You need single quote ' to wrap your parameter:
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
You should use single quotes (') for values
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
Also you can use like this to avoid SQL injection (See here)
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
I want to update 3 fields in a row in 3 columns but I don't know how to do it. I already searched google and searcedh here but couldn't find any solution for it. I want to change title, paragraph and category of a blog post using $_GET using this way:
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
when I use only one of $_title or $_txt, it works. But I couldn't find a way to update both fields together and couldnt update category selection.
full code of update.php page :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
$query = ("UPDATE tbl_post SET cat='$cat' WHERE id=$id");
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<?php
$id = $_GET['id'];
$query = "SELECT * FROM `tbl_post` WHERE(id=$id)";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C" value="<?php echo $rows['title'] ?>">
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"><?php echo $rows['txt'] ?></textarea>
<div class="clear"></div>
<?php } ?>
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
and insert.php :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$cat = $_POST['cat'];
$txt = $_POST['txt'];
echo 'title = '.$title.'<br>'.'category ='.$cat.'<br>'.'txt = '.$txt;
$query = "INSERT INTO tbl_post(`title`,`txt`,`cat_id`) VALUES ('$title','$txt','$cat')";
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C;">
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"></textarea>
<div class="clear"></div>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
Combine all the fields into a single query:
$title = $_POST['title'];
$txt = $_POST['txt'];
$cat = $_POST['cat'];
$query = "UPDATE tbl_post SET title='$title', txt = '$txt', cat = '$cat' WHERE id = $id";
Also, you should switch to parametrized queries instead of substituting into the SQL; this means using PDO or mysqli. Otherwise you need to escape the input data. See
How can I prevent SQL injection in PHP?
so I am trying to make a a online shop , basically what isn't working is to execute a query when the buy clicks the "BUY" button.The query is :
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
and the button is
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
The whole code :
<?php
$id = $_SESSION['SESS_MEMBER_ID'];
include ('config2.php');
$result = mysql_query("select * from shop_vehicule ORDER BY id DESC");
$result2 = mysql_query("select * from accounts where id = '$id'");
while($row = mysql_fetch_array($result2))
$credit = $row['credits'];
while($row = mysql_fetch_array($result)){
$name = $row['nume'];
$price = $row['pret'];
$left = $credit - $price;
$vehid = $row['vehid'];
echo "<p><center><b>$name</b> | $price </center>
More information about $name</p>
<div id=\"toPopup\">
<div class=\"close\"></div>
<span class=\"ecs_tooltip\">Press Esc to close <span class=\"arrow\"></span></span>
<div id=\"popup_content\"> <!--your content start-->
<p>
The $name costs $price, after you'll have $left !</p>
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
</div>
</div>
<div class=\"loader\"></div>
<div id=\"backgroundPopup\"></div>";
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
}
mysql_close();
?>
Here's my attempt to help, I didn't test the codes but it should be working. Please read the comments in the codes. It explains what it does.
$id = $_SESSION['SESS_MEMBER_ID'];
/* To use PDO the following line must be included in your config2.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASS', 'password');
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
You can either use define or put the info straight into the PDO() function but I like it when it's easy to read and modify if needed.
*/
include ('config2.php');
$query = $db->prepare("SELECT * FROM accounts WHERE id = :id"); //Please use PDO or MySQLi, MySQL is outdated and unsecure. For this example, I am using my favorite method which is PDO.
$query->execute(array(':id' => $id));
$account = $query->fetchObject(); //Since we only need one line, we're going to use fetchObject object.
$query2 = $db->prepare("SELECT * FROM shop_vehicule ORDER BY id DESC");
$query2->execute();
$vehicules = $query2->fetchAll(); //I am using fetchAll due to multiple row will be returned.
foreach ($vehicules as $row) {
echo '<p><center><b>'.$row['nume'].'</b> | '.$row['pret'].' </center>
More information about $name</p>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>The '.$row['nume'].' costs '.$row['pret'].', after you\'ll have '.$account->credit - $row['pret'].' !</p>
BUY
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>';
}
// Basically what this part does is whenever the user click on the link, purchase will be set and it'll trigger the query to insert into the vehicule table then return a message if it was successful or not.
if ( isset($_GET['purchase']) ) {
$query = $db->prepare("INSERT INTO vehicles (model,owner) VALUES (':vehid',':id');");
$query->execute(array(':vehid' => $_GET['purchase'], ':id' => $id));
if ($query) {
echo 'Congratulations! You have successfully purchased the vehicule!';
} else {
echo 'An error has occured, the purchase was not complete.';
}
}
Use action=$_SERVER['PHP_SELF'] in the form tag and make a write the MySQL Insert Code in condition where isset($_POST['Buy']) is true.
you can do this in php, but in 2 different files.
The first will have the form, and the second will read the POST value and perform the query
Example(please fill missing pieces)
File 1 . php
<form action="file2.php" method="post">
<input type="hidden" value=<?php echo $vehid;?>" name="vehid">
<input type="hidden" value=<?php echo $id;?>" name="id">
<input type="submit" value="BUY">
</form>
File2.php
$vehid=$_POST['model'];
$id=$_POST['id'];
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
For a complete tutorial see http://www.w3schools.com/php/php_mysql_insert.asp