This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I want to be able to pull my radio button value from a database and be able to edit it. How do I go about doing this? Everything inserts fine, but when I try and search I get an error of "Notice: Undefined index: isVolunteer in C:\xampp\htdocs\php_insert_update_delete_search.php on line 38"
My Code:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "2104299_test";
$personID = "";
$personFName = "";
$personLName = "";
$personAddress = "";
$personContact = "";
$personEmail = "";
$personPassword = "";
$isVolunteer = "";
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['personID'];
$posts[1] = $_POST['personFName'];
$posts[2] = $_POST['personLName'];
$posts[3] = $_POST['personAddress'];
$posts[4] = $_POST['personContact'];
$posts[5] = $_POST['personEmail'];
$posts[6] = $_POST['personPassword'];
$posts[7] = $_POST['isVolunteer'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM tbl_people WHERE personID = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$personID = $row['personID'];
$personFName = $row['personFName'];
$personLName = $row['personLName'];
$personAddress = $row['personAddress'];
$personContact = $row['personContact'];
$personEmail = $row['personEmail'];
$personPassword = $row['personPassword'];
$isVolunteer = $row['isVolunteer'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `tbl_people`(`personFName`, `personLName`, `personAddress`,`personContact`,`personEmail`,`personPassword`,`isVolunteer`)
VALUES ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]')";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
}
}
// Delete
if(isset($_POST['delete']))
{
$data = getPosts();
$delete_Query = "DELETE FROM `tbl_people` WHERE `personID` = $data[0]";
try{
$delete_Result = mysqli_query($connect, $delete_Query);
if($delete_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
}
} catch (Exception $ex) {
echo 'Error Delete '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `tbl_people` SET `personFName`= '$data[1]',`personLName`= '$data[2]',`personAddress`= '$data[3]',
`personContact`= '$data[4]',`personEmail`= '$data[5]',`personPassword`= '$data[6]',`isVolunteer`= '$data[7]'
WHERE `personID` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="php_insert_update_delete_search.php" method="post">
Person ID<br><input type="number" name="personID" placeholder="ID" value="<?php echo $personID;?>"><br><br>
First Name<br><input type="text" name="personFName" placeholder="First Name" value="<?php echo $personFName;?>"><br><br>
Last Name<br><input type="text" name="personLName" placeholder="Last Name" value="<?php echo $personLName;?>"><br><br>
Address<br><input type="text" name="personAddress" placeholder="Address" value="<?php echo $personAddress;?>"><br><br>
Contact Number<br><input type="mobile" name="personContact" placeholder="Contact" value="<?php echo $personContact;?>"><br><br>
Email<br><input type="email" name="personEmail" placeholder="Email" value="<?php echo $personEmail;?>"><br><br>
Password<br><input type="text" name="personPassword" placeholder="Password" value="<?php echo $personPassword;?>"><br><br>
Active Or Not:<br>
<input type="radio" name="isVolunteer" value="<?php echo $isVolunteer;?>" />Yes
<input type="radio" name="isVolunteer" value="<?php echo $isVolunteer;?>" />No
<br><br>
<div>
<!-- Input For Add Values To Database-->
<input type="submit" name="insert" value="Add">
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Clear Values -->
<input type="submit" name="delete" value="Delete">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
<div class="container">
<div class="main">
<form action="form.php" method="post">
<!---- Radio Button Starts Here ----->
<label class="heading">Radio Buttons :</label>
<input name="radio" type="radio" value="Radio 1">Radio 1
<input name="radio" type="radio" value="Radio 2">Radio 2
<input name="radio" type="radio" value="Radio 3">Radio 3
<input name="radio" type="radio" value="Radio 4">Radio 4
<?php include'radio_value.php'; ?>
<input name="submit" type="submit" value="Get Selected Values">
</form>
</div>
</div>
Link:-https://www.formget.com/php-select-option-and-php-radio-button/
Related
i have tried to fix my this upload code in my php :
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nama=$_SESSION["username"];
if (($nama)!='Admin'){
echo "<script>
window.location = '/home'
</script>";
}
?>
<h2>Upload Item Panel</h2>
<p><span class="error">*Semua harus diisi</span></p>
<form method="post" action="listingupload.php/" enctype="multipart/form-data">
Nama Barang: <input type="text" name="name" value="">
<br><br>
Stock :<input type="text" name="stock" value="">
<br><br>
Warna: <input type="text" name="warna" value="">
<br><br>
RAM: <input type="text" name="ram" value="">
<br><br>
kondisi: <input type="text" name="kondisi" value="">
<br><br>
Harga: <input type="text" name="harga" value="">
<br>
<b>Harap mengisi kolom harga tanpa titik (Dua juta rupiah = 2000000)</b>
<br><br>
Harga Sebelum diskon: <input type="text" name="hargabefore" value="">
<br><br>
Deskripsi: <textarea name="deskripsi" rows="5" cols="40"></textarea>
<br><br>
Gambar Listingan:<br><br>
<input type="file" name="pic"><br><br>
Gambar Detail 1:<br><br>
<input type="file" name="pic2"><br><br>
Gambar Detail 2:<br><br>
<input type="file" name="pic3"><br><br>
Gambar Detail 3:<br><br>
<input type="file" name="pic4"><br><br>
Gambar Detail 4:<br><br>
<input type="file" name="pic5"><br><br>
Gambar Detail 5:<br><br>
<input type="file" name="pic6"><br><br>
<input type="submit" value="POST" name="submit">
</form>
</body>
</html>
so that is the code for the form page
and here is the code for the POST method :
<?php
$namafile = $_FILES['pic']['name'];
$namafile2 = $_FILES['pic2']['name'];
$namafile3 = $_FILES['pic3']['name'];
$namafile4 = $_FILES['pic4']['name'];
$namafile5 = $_FILES['pic5']['name'];
$namafile6 = $_FILES['pic6']['name'];
$ukuran = $_FILES['pic']['size'];
$error = $_FILES['pic']['error'];
$ukuran2 = $_FILES['pic2']['size'];
$error2 = $_FILES['pic2']['error'];
$ukuran3 = $_FILES['pic3']['size'];
$error3 = $_FILES['pic3']['error'];
$ukuran4 = $_FILES['pic4']['size'];
$error4 = $_FILES['pic4']['error'];
$ukuran5 = $_FILES['pic5']['size'];
$error5 = $_FILES['pic5']['error'];
$ukuran6 = $_FILES['pic6']['size'];
$error6 = $_FILES['pic6']['error'];
include 'mysqldata.php';
$item=$_POST['name'];
$deskripsi=$_POST['deskripsi'];
$price=$_POST['harga'];
$stock=$_POST['stock'];
$ram=$_POST['ram'];
$warna=$_POST['warna'];
$kondisi=$_POST['kondisi'];
$hargabefore=$_POST['hargabefore'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn= new mysqli($host,$dbUsername,$dbPassword,$dbname);
if (mysqli_connect_error()){
echo mysqli_errno($this->db_link);
die('Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
} else{
echo "Redirecting....\n";
if (move_uploaded_file($_FILES['pic']['tmp_name'],'listing/'.$namafile)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic2']['tmp_name'],'listing/'.$namafile2)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic3']['tmp_name'],'listing/'.$namafile3)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic4']['tmp_name'],'listing/'.$namafile4)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic5']['tmp_name'],'listing/'.$namafile5)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic6']['tmp_name'],'listing/'.$namafile6)){
echo "Success";
}else{
echo "Failed";
}
$sql = "INSERT INTO $dbname.itemlist(Itemname, Description,Harga,Image,stock,picture,picture2,picture3,picture4,picture5,warna,ram,kondisi,pseudoprice) VALUES ('$item','$deskripsi','$price','$namafile','$stock','$namafile2','$namafile3','$namafile4','$namafile5','$namafile6','$warna','$ram','$kondisi','$hargabefore')";
$conn->query($sql);
}
?>
sometimes this works normally, so i got all of my data and my files uploaded to the mysql, BUT sometimes it just give me the PHP Notice of PHP Undefined Index for ALL OF my data including Price, Image, Stock etc.
I have no idea at all why could this happen, can anyone help me with this one?
EDIT :i did fill in all of the form data, but when i POST it, sometimes it still shows undefined index , the problem is that, if it shows UNDEFINED INDEX doesn't it mean that all of my data is not sent to the mysql? Because is did fill all of the data in my form, the problem is that in the POST script it told me that all of the data is NULL (Undefined index)
if i only uploaded 2-3 pictures the code is working, but if i uploaded 5 pictures then the undefined index error shows up
I am supposing that you have to check if form is submiited or not.
if(!empty($_POST) && !empty($_FILES))
{
$namafile = $_FILES['pic']['name'];
$namafile2 = $_FILES['pic2']['name'];
$namafile3 = $_FILES['pic3']['name'];
$namafile4 = $_FILES['pic4']['name'];
$namafile5 = $_FILES['pic5']['name'];
$namafile6 = $_FILES['pic6']['name'];
$ukuran = $_FILES['pic']['size'];
$error = $_FILES['pic']['error'];
$ukuran2 = $_FILES['pic2']['size'];
$error2 = $_FILES['pic2']['error'];
$ukuran3 = $_FILES['pic3']['size'];
$error3 = $_FILES['pic3']['error'];
$ukuran4 = $_FILES['pic4']['size'];
$error4 = $_FILES['pic4']['error'];
$ukuran5 = $_FILES['pic5']['size'];
$error5 = $_FILES['pic5']['error'];
$ukuran6 = $_FILES['pic6']['size'];
$error6 = $_FILES['pic6']['error'];
include 'mysqldata.php';
$item=$_POST['name'];
$deskripsi=$_POST['deskripsi'];
$price=$_POST['harga'];
$stock=$_POST['stock'];
$ram=$_POST['ram'];
$warna=$_POST['warna'];
$kondisi=$_POST['kondisi'];
$hargabefore=$_POST['hargabefore'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn= new mysqli($host,$dbUsername,$dbPassword,$dbname);
if (mysqli_connect_error()){
echo mysqli_errno($this->db_link);
die('Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
} else{
echo "Redirecting....\n";
if (move_uploaded_file($_FILES['pic']['tmp_name'],'listing/'.$namafile)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic2']['tmp_name'],'listing/'.$namafile2)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic3']['tmp_name'],'listing/'.$namafile3)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic4']['tmp_name'],'listing/'.$namafile4)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic5']['tmp_name'],'listing/'.$namafile5)){
echo "Success";
}else{
echo "Failed";
}
if (move_uploaded_file($_FILES['pic6']['tmp_name'],'listing/'.$namafile6)){
echo "Success";
}else{
echo "Failed";
}
$sql = "INSERT INTO $dbname.itemlist(Itemname, Description,Harga,Image,stock,picture,picture2,picture3,picture4,picture5,warna,ram,kondisi,pseudoprice) VALUES ('$item','$deskripsi','$price','$namafile','$stock','$namafile2','$namafile3','$namafile4','$namafile5','$namafile6','$warna','$ram','$kondisi','$hargabefore')";
$conn->query($sql);
}
}
Do this format to check if the variables have been set.
if (isset($_FILES['pic']['name']))
{
$namafile = $_FILES['pic']['name'];
}
if (isset($_POST['name']))
{
$item = $_POST['name'])
}
// do the rest
I'm trying to add form data into my database table on Xampp ,but while My echo displays everything properly ,it doesn't input anything into the database table and I wonder if I'm missing something here.I made sure to spell everything the same ,so I doubt it's a spelling error atleast....Any help,suggestions and or corrections are greatly appreciated !
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Pk = $Kiekis = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Vardas: <input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<br><br>
Pavarde: <input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<br><br>
Adresas: <input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error"><?php echo $AdErr;?></span>
<br><br>
Pk: <input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error"><?php echo $PkErr;?></span>
<br><br>
Kiekis:<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error"><?php echo $KiekErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Vardas;
echo "<br>";
echo $Pavarde;
echo "<br>";
echo $Adresas;
echo "<br>";
echo $Pk;
echo "<br>";
echo $Kiekis;
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Pk,Kiekis)VALUES('$Vardas','$Pavarde','$Adresas','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</body>
</html>
hi your are checking value in insert isset($_POST['insert']) but insert name not assign in any control so assign insert name to your submit control check below :
<input type="submit" value="Submit" name="insert">
I'm kinda confused with your code but I think the wrong part is in here:
<input type="submit" name="submit" value="Submit">
You have this submit but look at this:
if(isset($_POST['insert']))
You are trying to check if POST is set to insert instead of submit.
In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance
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.
In following code, how can I add a button or a link that sorts the data by 'name'?
The following code is just an example, a modified version of code that I found from http://fwebde.com/php/sqlite-php/ . The structure of the code is so enjoyable that I would like to improve it with a sorting-element.
Thanks!
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['name']) && isset($_POST['message'])) {
try {
$stmt = $db->prepare("INSERT INTO messages (name, message) VALUES (:name, :message);");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':message', $message);
$title = $_POST['name'];
$content = $_POST['message'];
$stmt->execute();
} catch (Exception $e) {
die ($e);
}
}try {
$posts = $db->prepare('SELECT * FROM messages;');
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $messages->fetchObject()): ?>
<?php echo $post->name ?>
<?php echo $post->message ?>
<?php endwhile; ?>
<form action="" method="post">
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['message'])) {
try {
//Insert data
} catch (Exception $e) {
die ($e);
}
}
try {
$order = "";
if(isset($_POST['sort'])){
$order = " ORDER BY `name`"; // Order list by name
$orderFlag = 1;
if(isset($_POST['order']) && $_POST['order'] == 1){
$order .= " DESC";
$orderFlag = 0;
}
}
$posts = $db->prepare("SELECT * FROM `messages`" . $order . ";");
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $posts ->fetchObject()): ?>
<?php echo $post->name ?><?php echo $post->message ?><br/>
<?php endwhile; ?>
<form action="" method="post">
<!--pushing this button sort by name -->
<input type="submit" name="sort" value="Sort by name" />
<input type="hidden" name="order" value="<?=$orderFlag?>" />
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<!--pushing this button insert new data -->
<input type="submit" name="submit" value="Submit" />
</form>