How to edit/update data in mysql using php - php

I've been researching everywhere regarding this matters and i still cant edit/update my entry. Noted, this is my first real program and my level is somewhat mediocre. So i would like to seek your advise/help regarding this matter.
CODE:
<?php
include('config.php');
if(isset($_POST['edit']))
{
$sql = "select * from hotels where BIL =" .$_GET['edit'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
if(isset($_POST['submit'])){
$hotel = $_POST['hotel'];
$address = $_POST['address'];
$update = "update hotels set $hotel = 'hotel', $address = 'address' where BIL = ".$_GET['edit'];
$up = mysqli_query($link, $update);
if (isset($sql)){
die ("Error $sql" .mysqli_connect_error());
}
else
{
header ("location: view.php");
}
}
?>
<html>
<body>
<form method="post" >
New Hotel: <br />
<textarea name="hotel" cols="50" rows="2" value="<?php echo $row['hotel']; ?>" /></textarea>
<br />
Address: <br / >
<textarea name="address" cols="50" rows="10" value="<?php echo $row['address']; ?>" /></textarea><br /><br />
<input type="submit" name="submit" value="update" />
</form>
<script>
function update(){
var x;
if(confirm("update Succesfully") == true){
x= "update";
}
}
</script>
</body>
</html>
Extra note: I copied this code from a youtube channel...
https://www.youtube.com/watch?v=jQzRDwY6zPc
Thanks in advance!

Related

PHP - Update SQL Statement mysqli database+Variables

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_REQUEST['teamname'];
$email = $_REQUEST['email'];
$password = (md5($_REQUEST['password']));
$query = "UPDATE users SET email = ?,password = ? WHERE name = ?";
$statemnt = $conn->prepare($query);
$statemnt->bind_param('sss',$email,$password,$name);
$statemnt->execute(); echo $name,$email,$password; var_dump();
$statemnt->close(); $conn->close(); } ?>
managed to get the SELECT Statement figured out before this one and still having issues with the UPDATE - a form above this php snippet and is suppose to fill out $email $password and $name
<form method="post" action="">Team Name:<br>
<input type="text" name="teamname" value="<?php echo $name;?>">
<br>Email:<br><input type="text" name="email" value="<?php echo $email;?>">
<br>Password:<br><input type="text" name="password" value="">
<br><br><input type="Submit" value="Update the Record" name="Submit">
</form>
EDITED TO THE FOLLOWING (there is code above this part and below dont expect u want to see the rest of my html code - the bottom is what i am have trouble with):SELECT STATEMENT and var_dump is working but when i enter a password into the form it doesnt trigger the Submit and ultimately the UPDATE Statement - i have worked on it today again to no avail. pls any help would be appreciated not sure what im doing wrong - also var_dump at the bottom is outputing all of the values now
<?php
if (isset($_POST['submit'])) {
$sql = $conn->prepare("UPDATE users SET email=? , password=? WHERE team=?");
$postedemail=$_POST['teamemail'];
$postedpassword= $_POST['teampassword'];
$sql->bind_param("ssi",$postedemail,$postedpassword,$_POST["mySelect"]);
if($sql->execute()) {
$success_message = "Edited Successfully";
} else {
$error_message = "Problem in Editing Record";
}
var_dump($postedpassword);
var_dump($postedemail);
}
$stmt = $conn->prepare("SELECT team, name, email, password FROM users WHERE team = ?");
$stmt->bind_param("i", $_POST["mySelect"]);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($rows = $result->fetch_assoc()) {
$name = $rows['name'];
$email = $rows['email'];
$password = $rows['password'];
}
var_dump($password);
var_dump($name);
var_dump($email);
var_dump($_POST['mySelect']);
$stmt->close();
?>
<?php if(!empty($success_message)) { ?>
<div class="success message"><?php echo $success_message; ?></div>
<?php } if(!empty($error_message)) { ?>
<div class="error message"><?php echo $error_message; ?></div>
<?php } ?>
<form name="frmUser" method="post" action="">
<label>NAME:</label>
<input type="text" name="teamname" class="txtField" value="<?php echo $name?>">
<label>EMAIL:</label>
<input type="text" name="teamemail" class="txtField" value="<?php echo $email?>">
<label>PASSWORD</label>
<input type="text" name="teampassword" class="txtField" value="">
<input type="submit" name="submit" value="Submit" class="demo-form-submit">
</form>
thanks
You have this at the begining of your script : $selectedOption = $_POST["mySelect"];
Nowhere in your code (especially in your <form></form>) I see any input named "mySelect"
Add this field in your form and the problem should be solved.
var_dump(); helps a lot debugging.

getting data by id from database after submitting to another page

I m trying to get data on another page by id which is on showdetails.php page.but i m unable to please help.
Showdetails.php
this page shows details of user with id and button which will allow user to edit details on another page
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body>
<?php
require('database.php');
?>
<h1>User Lists</h1>
<?php
$select = "SELECT id, firstname, lastname FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
while($row = mysqli_fetch_array($selectdata)) {
$id = $row['id'];
$first = $row['firstname'];
$last = $row['lastname'];
?>
<form method="get" action="editdetails.php">
<p><b>ID: <?php echo $id; ?></b></p>
<p>Name: <?php echo $first; ?> <?php echo $last; ?></p>
<?php
$edit = "SELECT id FROM signup WHERE id= '" .$id. "'";
$selectedit = $conn->query($edit);
?>
<p><input type="submit" name="display" value="Edit Details"></p>
</form>
<?php
}
}
?>
</body>
</html>
editdetails.php
On this page, user will be able to edit details, and i want details by id
<!DOCTYPE html>
<html>
<head>
<title>Edit User Details</title>
</head>
<body>
<?php
require('database.php');
$select = "SELECT firstname, lastname, age, phone_no, age, username, password FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
$row = mysqli_fetch_array($selectdata);
$first = $row['firstname'];
$last = $row['lastname'];
$age = $row['age'];
$phone_no = $row['phone_no'];
$username = $row['username'];
$password = $row['password'];
}
?>
<?php
if (isset($_POST['update'])) {
# code...
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$phone = mysqli_real_escape_string($conn, $_POST['phone_no']);
$username = mysqli_real_escape_string($conn, $_POST['user']);
$password = mysqli_real_escape_string($conn, $_POST['pass']);
$update = "UPDATE signup SET firstname= '$first', lastname= '$last', age= '$age', phone_no = '$phone', username = '$username', password = '$password' WHERE id= '$id'";
$updatedata = $conn->query($update);
if ($updatedata) {
# code...
echo $status = "Details Updated";
}
else {
# code...
echo $status = "Not Updated";
}
}
if (isset($_POST['delete'])) {
# code...
$delete = "DELETE FROM signup WHERE firstname = $first";
$deletedata = $conn->query($delete);
if ($deletedata) {
# code...
echo $status = "Details Deleted";
}
else {
# code...
echo $status = "Not Deleted";
}
}
?>
<h1>Edit Details</h1>
<form method="post" action= "<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<p>FirstName: <input type="text" name="first" value="<?php echo $first; ?>"></p>
<p>LastName: <input type="text" name="last" value="<?php echo $last; ?>"></p>
<p>Phone no: <input type="number" name="phone_no" value="<?php echo $phone_no; ?>"></p>
<p>Age: <input type="number" name="age" value="<?php echo $age; ?>"></p>
<p>User: <input type="text" name="user" value="<?php echo $username; ?>"></p>
<p>Password: <input type="password" name="pass" value="<?php echo $password; ?>"></p>
<p><input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete"></p>
</form>
<p><?php echo $status; ?></p>
</body>
</html>
Thank You.
Add in your HTML form a hidden input, like so:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Then in your editdetails.php file you can access it with: $_GET["id"].
Update:
Add the hidden input to the form in Showdetails.php.
Then in editdetails.php add at the top of the page $id = (int)$_GET["id"];
Then add to your SELECT query in editdetails.php a WHERE statement for selecting the correct user:
$select = "SELECT ... FROM signup WHERE id = $id";
For the update query you are then good to go since you are already using there WHERE id = $id. (but before your $id variable was not defined)

MySqli let user edit single record

learner here, going a little nuts..
i seem to be getting no errors, yet it is not updating.
connection is fine.
if(isset($_GET['edit_id'])){
$sql="SELECT * FROM info WHERE id=" .$_GET['edit_id'];
$result= mysqli_query($connect, $sql);
$row = mysqli_fetch_array($result);
}
//update
if(isset($_POST['btn-update'])){
$name=$_POST['name'];
$suname=$_POST['surname'];
$age=$_POST['age'];
$result=$_POST['result'];
$log=$_POST['log'];
$update="UPDATE employeeinfo SET name='$name', surname='$surname' WHERE id=". $_GET['edit_id'];
$up= mysqli_query($connect, $update);
if(!isset($sql)){
die("Error $sql" .mysqli_connect_error());
}
else
{
header("location: record.php");
}
}
and my calling
<html>
<body>
<h1>edit info<h1>
<form method="post">
name:<input type="text" class="form-control" name="name" value="<?php echo $row['name']; ?>"><br><br>
surname: <input type="text" name="surname" placeholder="Surname" value="<?php echo $row['surname']; ?>"><br><br>
log: <input type="text" name="log" placeholder="0" value="<?php echo $row['log']; ?>"><br><br>
<button type"submit" name"btn-update" id="btn-update" onclick="update()"><strong>Update</strong></button>
<button type="button" value="button">Cancel</button>
</form>
<script>
function update(){
var x;
if(confirm("Updated data Successfully") == true){
x = "update";
}
}
</script>
Not even sure if that script does anything, because my prompt said "update successful" yet clearly it wasnt. Thank you guys as always

after submitting the form it redirects to action page but do not save data in database

<?php
session_start();
include("includes/connection.php");
if(isset($_POST["testid"])&&isset($_POST["testtime"])&&isset($_POST["testdate"])&&isset($_POST["year"])&&isset($_POST["branch"]))
{
$tid = $_POST["testid"];
$ttime = $_POST["testtime"];
$tdate = $_POST["testdate"];
$year = $_POST["year"];
$branch = $_POST["branch"];
$query1 = "SELECT * FROM tbl_create_test";
$result1 = mysqli_query($conn,$query1);
$bool = true;
while($row = mysqli_fetch_array($result1))
{
$tidTemp= $row['fld_test_id'];
if($tidTemp==$tid)
{
$bool=false;
echo '<script>alert("This Test id is already Assigned");</script>' ;
echo '<script>window.location.assign("")</script>';
}
}
if($bool)
{
$query2 = "INSERT INTO tbl_create_test(fld_test_id,fld_test_time,fld_test_date,fld_year,fld_branch)
VALUES('$tid','$ttime','$tdate','$year','$branch')";
$result2 = mysqli_query($conn,$query2);
if($result2)
{
$_SESSION['test_id']=$tid;
header("location: enter_questions.php");
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Admin Area</title>
</head>
<body>
<h1 style="text-align:center;margin-top:40px;">WELCOME TO ADMIN AREA</h1>
<div style="width:50%; float:left;" >
<h2><u>Test Creation Section</u></h2>
<div style="padding:20px;">
<form method="post" action="enter_questions.php">
<label>Test id:<br><input type="text" name="testid" required></label></br>
<label>Test Time:<br><input type="time" name="testtime" required></label></br>
<label>Test Date:<br><input type="date" name="testdate" required></label></br>
<label>Year:<br><input type="text" name="year" required></label></br>
<label>Branch:<br><input type="text" name="branch" required></label></br>
<br><button type="submit" >Next</button>
</form>
</div>
</body>
</html>
The data is not saved in DB after clicking on next but it redirects to enter_questions page. I need to store data in DB so as to proceed. I am experienced in codeigniter but never did work on core PHP before.
Every form has a action, in your case you are saying to the form "When i click the button go to enter_questions.php". The form is going to listen you instruction and go to this file but nothing is there to do. If you want to run the code in the same place where your form is you can leave the action='' and make a submit button like this.
<input type='submit' name='submit' value='Click Me!'>
And know comes the question, How do you know when the button is clicked and run the code you want? Well you can do it this way.
if(isset($_POST['submit'])){
//run your code
}
You can read this article how forms work
<?php
session_start();
include("includes/connection.php");
if(isset($_POST["testid"])&&isset($_POST["testtime"])&&isset($_POST["testdate"])&&isset($_POST["year"])&&isset($_POST["branch"])) {
$tid = $_POST["testid"];
$ttime = $_POST["testtime"];
$tdate = $_POST["testdate"];
$year = $_POST["year"];
$branch = $_POST["branch"];
/// optimized code
if($result = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `fld_test_id` FROM tbl_create_test WHERE `fld_test_id`='$tid' LIMIT 1"))) {
if($result = mysqli_query($conn, "INSERT INTO tbl_create_test (fld_test_id,fld_test_time,fld_test_date,fld_year,fld_branch)
VALUES ('$tid','$ttime','$tdate','$year','$branch')")) {
$_SESSION['test_id']=$tid;
header("location: enter_questions.php");
die;
}
}
/// id exists or not insert record
echo '<script>alert("This Test id is already Assigned");</script>' ;
echo '<script>window.location.assign("")</script>';
}
?>
Just Remove the action from form. If it create problem then check your connection code in this include("includes/connection.php");
Edit2: I have try your code with mysql and it save the data into database
<?php
session_start();
mysql_connect('localhost','root','') or die('error');
mysql_select_db('dbp');
if(isset($_POST["testid"])&&isset($_POST["testtime"])&&isset($_POST["testdate"])&&isset($_POST["year"])&&isset($_POST["branch"]))
{
$tid = $_POST["testid"];
$ttime = $_POST["testtime"];
$tdate = $_POST["testdate"];
$year = $_POST["year"];
$branch = $_POST["branch"];
$query1 = "SELECT * FROM tbl_create_test";
$result1 = mysql_query($query1);
$bool = true;
while($row = mysql_fetch_array($result1))
{
$tidTemp= $row['fld_test_id'];
if($tidTemp==$tid)
{
$bool=false;
echo '<script>alert("This Test id is already Assigned");</script>' ;
echo '<script>window.location.assign("")</script>';
}
}
if($bool==true)
{
$query2 = "INSERT INTO tbl_create_test(fld_test_id,fld_test_time,fld_test_date,fld_year,fld_branch) VALUES('$tid','$ttime','$tdate','$year','$branch')";
$result2 = mysql_query($query2)or die('error in insertion');
if($result2)
{
$_SESSION['test_id']=$tid;
header("location: enter_questions.php");
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Admin Area</title>
</head>
<body>
<h1 style="text-align:center;margin-top:40px;">WELCOME TO ADMIN AREA</h1>
<div style="width:50%; float:left;" >
<h2><u>Test Creation Section</u></h2>
<div style="padding:20px;">
<form method="post" >
<label>Test id:<br><input type="text" name="testid" required></label></br>
<label>Test Time:<br><input type="time" name="testtime" required></label></br>
<label>Test Date:<br><input type="date" name="testdate" required></label></br>
<label>Year:<br><input type="text" name="year" required></label></br>
<label>Branch:<br><input type="text" name="branch" required></label></br>
<br><button type="submit" >Next</button>
</form>
</div>
</body>
</html>

How to validate input from database

i develop captcha that require the user to answer a question that randomly display. My database consist of id,question,answer. The problem is although i enter correct answer it still redirected me to error.php instead of success.php.
<?php
$database_db="test2";
$user_db="root";
$password_db="";
$host_db="localhost";
$link = mysqli_connect($host_db, $user_db, $password_db, $database_db);
/* check connection */
if (mysqli_connect_errno())
{
die ("couldnot connect: ".mysqli_connect_error());
exit();
}
if (array_key_exists("answer", $_POST) AND array_key_exists("question", $_POST))
{
$id = intval($_POST['question']);
$sql="SELECT question, answer FROM captcha WHERE question='$id' AND answer='".mysqli_real_escape_string($link, $_POST['answer'])."'";
$result = mysqli_query($link, $sql) or exit('$sql failed: '.mysqli_error($link));
$num_rows = mysqli_num_rows($result);
if($num_rows > 0)
{
header("Location: success.php");
}
else
{
header("Location: error.php");
}
exit;
}
else
{
$query = "SELECT id, question FROM `captcha` ORDER BY RAND() LIMIT 1";
if ($result = mysqli_query($link, $query))
{
if ($row = mysqli_fetch_assoc($result))
{
$id = $row["id"];
$question = $row["question"];
}
}
}
?>
<html>
<body>
<form method="post">
<?php echo $question; ?><br />
<input type="hidden" name="question" id="question" value="<?php echo $id; ?>" />
<input type="text" name="answer" id="answer" /><br />
<input type="submit" name="submit" value="submit" /><br />
</form>
</body>
</html>
It looks like you're querying the wrong column for a match to $id:
"SELECT question, answer FROM captcha WHERE question='$id' AND ... "
I think this should be:
"SELECT question, answer FROM captcha WHERE id='$id' AND ... "

Categories