Data not updating in PHP mysql - php

Message show:
Product not updated!
Not updating through form. Rest of the code is working fine. Database is working fine. I think problem is in update query.
HTML form is in product.php and Controller is in product-controller.php and function code is in admin-model.php.
Select insert and delete query is working but update query is not working I don't understand why.
HTML Form
<form action="product-controller.php?type=update" method="post">
<input type="hidden" value="<?php echo $r["productid"]; ?>" name="productID" id="productID"/>
<div>
<label>Product Name</label>
<input type="text" value="<?php echo $r["product_name"]; ?>" name="productName" placeholder="Product Name">
</div>
<div>
<label>Product Price</label>
<input type="number" value="<?php echo $r["product_price"]; ?>" name="productPrice" placeholder="Product Price">
</div>
<div>
<label>Product Quantity</label>
<input type="number" value="<?php echo $r["product_quantity"]; ?>" name="productQuantity" placeholder="Product Quantity">
</div>
<div>
<label>Product Description</label>
<textarea name="productDesc"><?php echo $r["product_description"]; ?></textarea>
</div>
<div>
<button type="submit">Update Product</button>
</div>
</form>
Controller
<?php
include("admin-model.php");
if(isset($_GET["type"]))
{
$dbobj=new AdminModel;
if($_GET["type"]=="add")
{
$name=$_POST["productName"];
$price=$_POST["productPrice"];
$quantity=$_POST["productQuanity"];
$desc=$_POST["productDesc"];
$res=$dbobj->addProduct($name, $price, $quantity, $desc);
if($res>0)
{
header("Location: product.php?msg=sucess");
}
else
{
header("Location: product.php?msg=fail");
}
}
else if($_GET["type"]=="update")
{
$id=$_POST["productID"];
$name=$_POST["productName"];
$price=$_POST["productPrice"];
$quantity=$_POST["productQuantity"];
$desc=$_POST["productDesc"];
$res=$dbobj->updateProduct($id, $name, $price, $quantity, $desc);
if($res>0)
{
header("Location: product.php?msg=upsucess");
}
else
{
header("Location: product.php?msg=upfail");
}
}
else if($_GET["type"]=="del")
{
$id=$_GET["productID"];
$res=$dbobj->deleteProduct($id);
if($res>0)
{
header("Location: product.php?msg=delsucess");
}
else
{
header("Location: product.php?msg=delfail");
}
}
}
else
{
header("Location: product.php");
}
?>
Function Code
<?php
class AdminModel
{
var $con, $com;
var $res;
public function __construct()
{
$this->con=mysql_connect("localhost", "root", "");
mysql_select_db("mywebsitedb");
}
public function updateProduct($id, $name, $price, $quantity, $desc)
{
$this->com=mysql_query("update product set product_name='$name', product_price='$price', product_quantity='$quantity', product_description='$desc', where productid='$id'", $this->con);
return $this->com;
}

Please correct your update query as follows:
$this->com=mysql_query("update product set product_name='$name', product_price='$price', product_quantity='$quantity', product_description='$desc' where productid='$id'", $this->con);

This Query SQL is wrong syntax :
update product set product_name='$name', product_price='$price',
product_quantity='$quantity', product_description='$desc', where productid='$id'
-->
update product set product_name='$name', product_price='$price',
product_quantity='$quantity', product_description='$desc' where productid='$id'

Related

how to make my wordpress plugin redirect to form successful page or failed page

I have created a plugin that will insert data into my local database. But upon submission, I want to redirect to a successful page or an unsuccessful page or a duplicate record page. Below is my plugin code. When hitting submit the database insert works just fine, but I get a 404 error for the redirect pages. No errors in php, apache or mysql logs either.
<?php
/*
plugin name: deano plugin
description: deano test database to insert data into books table
author: Dean-O
*/
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once($path.'/wp-load.php');
function deanoinsertdata() {
/**
* Dean-O database insert book function
*/
global $wpdb;
if(isset($_POST['submitbtn'])){
$data=array(
'wp_id'=>$_POST['wp_id'],
'title'=>$_POST['title'],
'author'=>$_POST['author'],
);
$table_name = 'books';
$foundOne = 1;
$wp_idin = $_POST['wp_id'];
$titlein = $_POST['title'];
$authorin = $_POST['author'];
/*echo ($wp_idin);
echo ($titlein);
echo ($authorin);
*/
/*
see if the record is already in the table
*/
$sql = "select * from books";
print $sql;
$results = $wpdb->get_results($sql);
foreach($results as $result) {
if($result->wp_id==$wp_idin && $result->title==$titlein && $result->author==$authorin)
{
$foundOne = 0;
}
}
if($foundOne==1) {
$resultinsert = $wpdb->insert($table_name,$data, $format=NULL);
if($resultinsert==1) {
//header('Location: http://localhost/tadpolewp/deano-plugin-successful/');
error_log( 'successful' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/", 301 );
//error_log('Book saved 1');
//echo "Book Saved 1";
} else {
//header('Location: http://localhost/tadpolewp/deano-plugin-failed/');
error_log( 'failed to save' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-failed/", 301 );
//error_log('unable to save');
//echo "Unable to Save";
}
} else {
//error_log('Duplicate record found');
//echo "Duplicate recortd found";
//header('Location: http://localhost/tadpolewp/deano-plugin-duplicate-records/');
error_log( 'duplicate record' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin--duplicate-records/", 301 );
}
}
?>
<form role="form" method="post">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Book Title</label>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" class="form-control input-sm" required="">
</div>
<div class="form-group">
<label>Book Author</label>
<input id="author" name="author" type="text" placeholder="Primary Author" class="form-control input-sm" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
my bad... I forgot the exit(); after each redirect. Problem solved.

jQuery AJAX Update and Show/Hide Div

Need some help doing my update Ajax call. What I want my code to do is to show when on click my update form and pass the data from the form to my update via AJAX. So far the form isn't showing on click nor is the update working. Everything else seems to be working right except for that.
index.php
<?php include 'includes/header.php' ?>
<div class="main" id="maincontent">
<div class="main-section">
<div class="add-section">
<form action="app/add.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
<?php
$todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
?>
<div class="show-todo-section">
<?php if($todos->rowCount() <= 0){?>
<div class="todo-item">
<div class="empty">
<p>Enter a To Do!</p>
<img src="img/f.jpg" alt="Notebook" width="100%" height="175px" />
</div>
</div>
<?php } ?>
<?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="todo-item">
<span id="<?php echo $todo['id']; ?>" class="remove-to-do" aria-label="Delete"><i class="fa fa-trash" style="font-size:18px"></i></span>
<span id="<?php echo $todo['id']; ?>" class="update-to-do" aria-label="Edit">
<i class="fa fa-pencil" style="font-size:18px"></i></span>
<?php if($todo['checked']) { ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box" checked />
<h2 class="checked"><?php echo $todo['title'] ?></h2>
<?php }else{ ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box">
<h2><?php echo $todo['title'] ?></h2>
<?php } ?>
<br>
<small>Created: <?php echo $todo['date_time'] ?> </small>
<div style="display:none;" class="update"><?php include 'updateForm.php'?></div>
<!---->
</div>
<?php } ?>
jQuery
<script>
$(document).ready(function(){
$('.remove-to-do').click(function(){
const id = $(this).attr('id');
$.post("app/remove.php",
{
id: id
},
(data) =>{
if(data){
$(this).parent().hide(600);
}
}
);
});
$(".check-box").click(function(e){
const id = $(this).attr('data-todo-id');
$.post("app/check.php",
{
id: id
},
(data) =>{
if(data != 'error')
{
const h2 = $(this).next();
if(data === '1'){
h2.removeClass('checked');
}else{
h2.addClass('checked');
}
}
}
);
}); /* */
$(".update-to-do").click(function(e){
const id = $(this).attr('id');
var title = $(this).attr('id'); //find
var month = $(this).attr('id');
var year = $(this).attr('id');
$.post("app/update.php",
{
id: id,
title: title,
month: month,
year : year
},
(data) =>{
//alert(id);
if(data != 'error')
{
var x = document.getElementsByClassName(".update");
if(form.hide()){
form.show();
}else{
form.hide();
}
}
}
);
});
});
updateForm.php
<div class="add-section">
<form action="app/update.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="id" style="display:none;"></label>
<input type="hidden" id= "id" name="id" value="<?php echo $_GET['id']; ?>" aria-label=""/>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="id" style="display:none;"></label>
<!--<input type="hidden" id= "id" name="id" value="<?php //echo $_GET['id']; ?>" aria-label="id"/> -->
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<div class="pad"></div>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
update.php
<?php
if(isset($_POST['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
$title = $_POST['titleUp'];
$month = $_POST['monthUp'];
$year = $_POST['yearUp'];
$dateMonth;
$futureDate;
if(empty($id))
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
else
{
if( (!empty($title)) && (empty($month)) && (empty($year)) )
{ //need to filter 0 so its registered as not empty
$title = validTitle($title);
$stmt = $conn->prepare("UPDATE todos(title) VALUE(?) WHERE id=?");
$res = $stmt->execute([$title, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (empty($year)) )
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = date("Y");
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (!(empty($year))))
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = validYear($year);
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
}
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
?>
You are POSTing to the page but checking for GET.
Good manual pages to read:
Handling external variables
Example:
$.post("app/update.php",
{
id: id
alert(id);
},
That will send a POST to the app/update.php script you have which contains the following:
<?php
// $GET is not the same as $_GET
if(isset($GET['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $GET['id'];
echo $id;
This will not work given that you are POSTing but looking incorrectly at $GET (which should be $_GET).
To fix change the following lines to:
<?php
if($_POST['id']){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
Please note that $GET and $_GET aren't the same things, nor are $POST and $_POST.

How to fix the Add function?

I'm doing a php based project.And I want to add data to the database.I did it using php, PDO. And I created the code with OOC. But There's a if else part in main HTML page. In that part the else part is running. But I didn't even click the insert button. When the page is loading the else part is running. I watched a video and this code is working perfectly fine. Here's the code..
Insert.php - Getters, Setters, SQL query and etc.
class Stock
{
protected $ItemNo;
protected $ItemName;
protected $brand;
protected $qty;
protected $Description;
protected $ItemDate;
protected $SupplierName;
protected $SupplierMail;
private $tableName = 'StockDetails';
private $dbconn;
function setItemNo($ItemNo) { $this->ItemNo = $ItemNo; }
function getItemNo() { return $this->ItemNo; }
function setItemName($ItemName) { $this->ItemName = $ItemName; }
function getItemName() { return $this->ItemName; }
function setBrand($brand) { $this->brand = $brand; }
function getBrand() { return $this->brand; }
function setQty($qty) { $this->qty = $qty; }
function getQty() { return $this->qty; }
function setDescription($Description) { $this->Description = $Description; }
function getDescription() { return $this->Description; }
function setItemDate($ItemDate) { $this->ItemDate = $ItemDate; }
function getItemDate() { return $this->ItemDate; }
function setSupplierName($SupplierName) { $this->SupplierName = $SupplierName; }
function getSupplierName() { return $this->SupplierName; }
function setSupplierMail($SupplierMail) { $this->SupplierMail = $SupplierMail; }
function getSupplierMail() { return $this->SupplierMail; }
public function __construct()
{
require_once ('Database.php');
$db = new Database();
$this->dbconn = $db->connect();
}
public function insert(){
$sql = "INSERT INTO $this->tableName VALUES (:ItemNo, :ItemName, :brand, :qty, :Description, :ItemDate, :SupplierName, :SupplierMail)";
$stmt = $this->dbconn->prepare($sql);
$stmt->bindParam(':ItemNo', $this->ItemNo);
$stmt->bindParam(':ItemName', $this->ItemName);
$stmt->bindParam(':brand', $this->brand);
$stmt->bindParam(':qty', $this->qty);
$stmt->bindParam(':Description', $this->Description);
$stmt->bindParam(':ItemDate', $this->ItemDate);
$stmt->bindParam(':SupplierName', $this->SupplierName);
$stmt->bindParam(':SupplierMail', $this->SupplierMail);
if($stmt->execute()){
return true;
}else{
return false;
}}}
?>
Action.php - Form action on AddItem.php
require_once ('Insert.php');
class action{
function __construct(){
switch ($_POST['submit']) {
case 'insert':
$obInsert = new Stock;
$obInsert->setItemNo($_POST['ItemNo']);
$obInsert->setItemName($_POST['ItemName']);
$obInsert->setBrand($_POST['brand']);
$obInsert->setQty($_POST['qty']);
$obInsert->setDescription($_POST['Description']);
$obInsert->setItemDate(date('Y-m-d H:i:s'));
$obInsert->setSupplierName($_POST['SupplierName']);
$obInsert->setSupplierMail($_POST['SupplierMail']);
if($obInsert->insert()) {
header('location: AddItem.php?insert=1');
} else{
header('location: AddItem.php?insert=0');
}
break;
default:
header('location: AddItem.php');
break;
}
}
}
if(isset($_POST['submit'])){
$object = new action;
}
AddItem.php
To get the brand and ItemName from the Database. The brand changes according to ItemName.
<?php
require_once ('GetBrand.php');
$ItemName = LoadItemName();
?>
$(document).ready(function(){
$("#ItemName").change(function(){
var aid = $("#ItemName").val();
$.ajax({
url: 'GetBrand.php',
method: 'post',
data: 'aid=' + aid
}).done(function(brand){
console.log(brand);
brand = JSON.parse(brand);
$('#brand').empty();
brand.forEach(function(bnamee){
$('#brand').append('<option>' + bnamee.brand + '</option>')
})
})
})
})
The Form
<form name="form0" method="post" action="Action.php">
<div class="form-group">
<label for="text">Item No</label>
<input type="text" name="ItemNo" id="ItemNo" placeholder="Item No" required>
</div>
<form name="form1" action="AddItem.php" method="post">
<div class="form-group">
<label for="text">Item Name</label>
<table>
<tr>
<td><select name="ItemName" id="ItemName" required>
<option value="" disabled="" selected>Select Name</option>
<?php foreach($ItemName as $iname)
echo "<option id='".$iname['ItemNo']."' value='".$iname['ItemNo']."'>".$iname['ItemName']."</option>";
?>
</select></td>
<td><label for="text">Add Item Name : </label></td>
<td><input type="text" name="name" id="name"> </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
<div class="form-group">
<label for="text">Brand Name</label>
<table>
<tr>
<td><select name="brand" id="brand" required>
<option value="">Select Brand</option>
</select></td>
<td<label for="text">Add Brand : </label></td>
<td><input type="text" name="Bname" id="Bname" class="form-control" > </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
</form>
<div class="form-group">
<label for="text">Quantity</label>
<input type="text" name="qty" id="qty" placeholder="Quantity" required>
</div>
<div class="form-group">
<label for="text">Item Description</label>
<input type="text" name="Description" id="Description" placeholder="Description" required>
</div>
<div class="form-group">
<label for="text">Date</label>
<input type="date" name="ItemDate" id="ItemDate" required>
</div>
<div class="form-group">
<label for="text">Supplier Name</label>
<input type="text" name="SupplierName" id="SupplierName" placeholder="Supplier Name" required>
</div>
<div class="form-group">
<label for="text">Supplier Mail</label>
<input type="text" name="SupplierMail" id="SupplierMail" placeholder="Supplier Mail" required>
</div><br/>
<div class="form-group">
<button id="submit" name="submit" value="insert">Insert</button>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
</div>
</form>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
you are surprised that this runs?
What you have said here is, if there is a $_GET parameter called insert and it's equal to 1 then echo "inserted..." in any other situation that may exist echo 'oops...'
Php cannot naturally discern whether this is the initial page load, a redirect, a button has been pressed or what you are thinking. If you only want this to run if a button has been been clicked you'd need to add in some extra checks around the whole thing, for example
if(isset($_POST['submit'])) {
///add in your checks to
}
or possibly more suitable for you would be
if(isset($_GET['insert']) {
if($_GET['insert'] == 1)){
echo "Inserted Successfully ";
} else {// you're missing a brace here
echo "Ooops..! Something went wrong.";
}
}
the point is, your code will always run regardless at the moment because it is an if/else i.e. do this or do that - but what you want to say is if a - do b or c, else do nothing. I think you need to try and understand exactly how conditionals work

hii i'm trying to learn pdo over mysqli so i want to know how i can change my existing code using store procedure

first i'm creating functions which call store procedure so i want to do the same with pdo i have tried different ways searched a lot but couldnt find a proper solution
my function.php
<?php
function AddWords($word,$meaning,$synonym,$antonym){
include("conn.php");
$result=mysqli_query($conn,"CALL AddWords('$word','$meaning','$synonym','$antonym')");
//echo "CALL AddWords('$word','$meaning','$synonym','$antonym')";
return $result;
}
function GetWords($word){
include("conn.php");
$result=mysqli_query($conn,"CALL GetWords('$word')");
return $result;
}
function GetAdminWords(){
include("conn.php");
$result=mysqli_query($conn,"CALL GetAdminWords()");
return $result;
}
function GetWordsByID($id){
include("conn.php");
$result=mysqli_query($conn,"CALL GetWordsById($id)");
return $result;
}
function Deletewords($id){
include("conn.php");
$result=mysqli_query($conn,"CAll DeleteWords($id)");
return $result;
}
function UpdateWords($word,$meaning,$synonym,$antonym,$id){
include("conn.php");
$result=mysqli_query($conn,"CALL UpdateWords('$word','$meaning','$synonym','$antonym',$id)");
//echo "CALL UpdateWords('$word','$meaning','$synonym','$antonym',$id)";
return $result;
}
function SortContent(){
include("conn.php");
$result=mysqli_query($conn,"CALL SortContent()");
return $result;
}
function SortContent2(){
include("conn.php");
$result=mysqli_query($conn,"CALL SortContent2()");
return $result;
}
?>
then call this function in main file where i'm using mysqli_escape_string
which i want to achieve in pdo
my main file
<?php
include("conn.php");
include("function.php");
if(isset($_POST['btn_submit'])){
$word=$_POST['word'];
$meaning=$_POST['meaning'];
$antonym=$_POST['antonym'];
$synonym=$_POST['synonym'];
if(!isset($_GET['id1'])){
$result=AddWords(mysqli_escape_string($conn,$word),mysqli_escape_string($conn,$meaning),mysqli_escape_string($conn,$synonym),mysqli_escape_string($conn,$antonym));
echo "<script type='text/javascript'>alert('Saved Successfully!!')</script>";
echo "<script type='text/javascript'>window.location='view.php'</script>";
}
if(isset($_GET['id1'])){
//echo $_GET['id1'];
$id=$_GET['id1'];
$result=UpdateWords(mysqli_escape_string($conn,$word),mysqli_escape_string($conn,$meaning),mysqli_escape_string($conn,$synonym),mysqli_escape_string($conn,$antonym),$id,$conn);
echo "<script type='text/javascript'>alert('Saved Successfully!!')</script>";
echo "<script type='text/javascript'>window.location='view.php'</script>";
}
}
?>
in my code i'm mostly using mysqli_escape_string
<?php
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById(mysqli_escape_string($conn,$id));
if(mysqli_num_rows($result)>0)
$row=mysqli_fetch_array($result);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
?>
<form method="post">
<div class="container container-fluid">
<div class="form-group">
<div class="col-xs-4">
<label for="inputdefault">Add Word</label>
<input class="form-control" id="inputdefault" type="text" name="word" value="<?php if(isset($word)){echo $word;}?>">
<label for="inputdefault">Add Meaning</label>
<input class="form-control" id="inputdefault" type="text" name="meaning" value="<?php if(isset($meaning)){echo $meaning;}?>">
<label for="inputdefault">Add Synonym</label>
<input class="form-control" id="inputdefault" type="text" name="synonym" value="<?php if(isset($synonym)){echo $synonym;}?>">
<label for="inputdefault">Add Antonym</label>
<input class="form-control" id="inputdefault" type="text" name="antonym" value="<?php if(isset($antonym)){echo $antonym;}?>"><br>
<button type="submit" class="btn btn-primary" name="btn_submit" >Submit</button>

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

Categories