$_GET variable not seen inside if statement - php

I have passed a variable using GET to a new page and will like to insert the value into a table in my database but it is saying undefined variable $exex. I tried to echo it inside the 'submit' if statement but it is not seen there either. It only echo the variable inside the isset GET if statement.
Below is the code:
<?php
session_start();
include "includes/connec.inc.php";
if (isset($_GET['exid'])){
$exex=$_GET['exid'];
}
$sql = "SELECT id FROM eaouser WHERE email = '" . $_SESSION['email'] . "'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
$eaofid=$row['id'];
if (isset($_POST['submit'])){
if (isset($_POST['feedbacks'])){
$feedback = $_POST['feedbacks'];
if (!empty($feedback)){
$INSERT = "INSERT Into feedback (exfid,eaofid,comment) values(?,?,?)";
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("iis", $exex, $eaofid, $feedback);
$stmt->execute();
if ($stmt==TRUE){
echo "<script> alert('Feedback sent!');
window.location='feedback.php'
</script>";
}else{
echo "<script> alert('Error sending feedback!');
window.location='feedback.php'
</script>";
}
}else{
echo "<script> alert('Feedback form is empty!');
window.location='feedback.php'
</script>";
}
}
}
HTML:
<div class="panel-body">
<form method="POST" action="feedback.php">
<div class="form-group">
<label for="message-text" class="col-form-label">Comment on the experiment:</label>
<textarea class="form-control" name="feedbacks" cols="142" rows="5" placeholder="Type here..."></textarea>
<br>
<button type="submit" name="submit" class="btn" style="background-color: purple;color: white">Send feedback</button>
</div>
</form>
</div>

Related

It tried updating to database but it is not working

<?php
include('config/db_connect.php');
$title = $email = $ingredients ='';
$errors = array('email'=>'', 'title'=>'', 'ingredient'=>'');
if(isset($_POST['update'])){
//Check email
if(empty($_POST['email'])){
$errors['email'] ='an email is required <br />';
} else{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = 'Email must be a valid email address';
}
}
//Check title
if(empty($_POST['title'])){
$errors['title'] ='a title is required <br />';
} else{
$title = $_POST['title'];
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$errors['title'] = 'Title must be letters and spaces only';
}
}
//Check ingredients
if(empty($_POST['ingredients'])){
$errors['ingredient'] = 'at least one ingredent is required <br />';
} else{
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$errors['ingredient'] = 'ingredients must be a comma separated list';
}
}
if(array_filter($errors)){
//echo 'errors in the form';
}else{
$id_to_update = mysqli_real_escape_string($conn, $_POST['$id_to_update']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
//create SQL
$sql = "UPDATE pizzas SET email='$email', title='$title', ingredients='$ingredients' WHERE id=$id_to_update";
echo $sql;
//save to db and check
if(mysqli_query($conn, $sql)){
//sucess
header('Location: index.php');
}else{
//errors
echo 'query error =' .mysqli_error($conn);
}
}
}
//check GET Request id param
if(isset($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);
// make sql
$sql = "SELECT * FROM pizzas WHERE id = $id";
//get query result
$result = mysqli_query($conn, $sql);
//fetch result in array format
$pizza = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<section class="container grey-text">
<h4 class="center">Edit Pizza</h4>
<form class="white" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<label >Your Email:</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($pizza['email']); ?>">
<div class="red-text"><?php echo $errors['email']; ?></div>
<label >Pizza Title:</label>
<input type="text" name="title" value="<?php echo htmlspecialchars($pizza['title']); ?>">
<div class="red-text"><?php echo $errors['title']; ?></div>
<label >ingredients(comma separated):</label>
<input type="text" name="ingredients" value="<?php echo htmlspecialchars($pizza['ingredients']); ?>">
<div class="red-text"><?php echo $errors['ingredient']; ?></div>
<div class="center">
<input type="submit" name="update" value="Update Pizza" class="btn brand z-depth-0">
Back
</div>
</form>
</section>
<?php include('templates/footer.php');?>
</html>
Undefined index: $id_to_update in C:\xampp\htdocs\pizza\edit.php on line 36
UPDATE pizzas SET email='ajisafejerry#gmail.com', title='fish Supreme', ingredients='fish, tomatoes, cheese, pepper' WHERE id=query error =You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
You missed to post the "id" in your form you should add it.
<input type="hidden" name="id_to_update" value="<?php echo $id ?>">
And you have a typo, remove the dollar sign, it is a name not a variable.
$id_to_update = mysqli_real_escape_string($conn, $_POST['id_to_update']);
// ^ here
And if you want, depending on your specifications, you can tweak your redirect after the update to smth. like this.
header('Location: sql.php?id='.$id_to_update);

Problem: Can't update the db value type text when i change the content of text area

I'm trying to update the variable description with the value of the textarea.
Here is my html:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" value="<?php echo $animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animal-Description" cols="30" rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
Here is my php code to update the description variable:
//if the update button is clicked
if (isset($_POST['update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
}
else {
$idQuery = "UPDATE animals SET description='$animalDesription' WHERE id_num='$id'";
$stmt = $conn->prepare($idQuery);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}
When I enter an existent Id and some text in the textarea, it does nothing just refresh the page.
Try:
<form action="index.php" method="post">
<div class="search">
<label for="animalId">Search for Id</label><br>
<input type="text" name="animalId" id = "animalId" value="<?php echo
$animalId; ?>">
</div>
<div class="animal_description">
<label for="animalDescription">Animal's description:</label><br>
<textarea name="animalDescription" id="animalDescription" cols="30"
rows="10"><?php echo
$animalDescription; ?></textarea>
</div>
<button type="submit" name="Update">Update</button>
</form>
//if the update button is clicked
if (isset($_POST['Update'])) {
//getting variable
$animalId = $_POST['animalId'];
$animalDescription = $_POST['animalDescription'];
//checking if any empty field
if(empty($animalId)){
$ERRORS['animal-description'] = "The id field is requiered";
} else {
$idQuery = "UPDATE animals SET description=? WHERE
id_num=?";
$stmt = $conn->prepare($idQuery);
$stmt->bind_param("si", $animalDescription, $animalId);
if ($stmt->execute()) {
$ERRORS['final-message'] = "Successfully updated the database";
}
else {
$ERRORS['final-message'] = "Failed to connect";
}
}
}

Update row data with id not carrying id forward

Have being trying this query for 3 days now. I have a list of rows here: http://prntscr.com/dick00. All what I want to is to edit and delete each row respectively. For some reason the id is not carrying forward and no record is updating.
When I click on edit in access.php I get edit_access.php?id= in address bar.
Here is my link in access.php
<td><a href="edit_access.php?id=<?php echo $row['id']; ?>"><i class="fa fa-edit"></i>edit</td>
edit_access.php
EDIT 1: php code
<?php
// start session
session_start();
// error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['user_type'])){
header('Location: index.php');
}
// include connection
require_once('include/connection.php');
// set user session variables
$userId = $_SESSION['user_id'];
$error = [] ;
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$therapist = $_POST['therapist'];
$access_type = $_POST['access_type'];
$code = $_POST['code'];
$created_at = $_POST['created_at'];
$postcode = $_POST['postcode'];
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter patient first name';
}
if (empty($lastname)){
$error[] = 'Field empty, please enter patient last name';
}
if (empty($therapist)){
$error[] = 'Field empty, please enter your name';
// $error = true;
}
if (empty($code)){
$error[] = 'Field empty, please enter patient access code';
// $error = true;
}
if (empty($access_type)){
$error[] = 'Field empty, please check access type';
// $error = true;
}
if (empty($postcode)){
$error[] = 'Field empty, please enter patient postcode';
// $error = true;
}
//if no errors have been created carry on
if(empty($error)){
$updated_at = date('Y-m-d');
// ************* UPDATE PROFILE INFORMATION ************************//
if(!($stmt = $con->prepare("UPDATE access SET firstname = ?, lastname = ?, therapist = ?, access_type = ?, postcode = ?, code = ?, updated_at = ?
WHERE id = ?"))) {
echo "Prepare failed: (" . $con->errno . ")" . $con->error;
}
if(!$stmt->bind_param('sssssssi', $firstname, $lastname, $therapist, $access_type, $postcode, $code, $updated_at, $userId)){
echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
}
if($stmt) {
$_SESSION['main_notice'] = '<div class="alert alert-success">"Access Code Added successfully!"</div>';
header('Location: access.php');
exit;
}else{
$_SESSION['main_notice'] = '<div class="alert alert-danger">"Some error, try again"</div>';
header('Location: '.$_SERVER['PHP_SELF']);
}
}
}
// title page
$title = "Edit Access Record | Allocation | The Whittington Center";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_GET['id'])){
$userId = $_GET['id'];
}
else{
$userId = $_POST['user_id'];
// mysqli_close($con);
$stmt = $con->prepare("SELECT * FROM access WHERE id = ?");
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
echo 'No Data Found for this user';
}else {
$stmt->bind_result($firstname, $lastname, $therapist, $access_type, $postcode, $code);
while ($row = $stmt->fetch());
$stmt->close();
}
?>
EDIT 2: HTML part
<h2 class="text-light text-greensea">Edit Access Record</h2>
<form name="access" class="form-validation mt-20" novalidate="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete='off'>
<div class="form-group">
<input type="text" name="firstname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' firstname ']; } ?>' placeholder='firstname'></td>
</div>
<div class="form-group">
<input type="text" name="lastname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' lastname ']; } ?>' placeholder='lastname'></td>
</div>
<div class="form-group">
<input type="text" name="therapist" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' therapist ']; } ?>' placeholder='therapist'></td>
</div>
<?php $access_type = $access_type; ?>
<div class="form-group ">
<label for="work status">Access Type</label>
<div name="access_type" value='<?php if(isset($error)){ echo $_POST[' access_type ']; } ?>'>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($work_status) && $access_type == "Keysafe") echo "checked"; ?> value="Keysafe"><i></i>Keysafe
</label>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($access_type) && $access_type == "keylog") echo "checked"; ?> value="keylog"><i></i>Keylog
</label>
</div>
</div>
<div class="form-group">
<input type="text" name="code" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' code ']; } ?>' placeholder='access code'></td>
</div>
<div class="form-group">
<input type="text" name="postcode" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' postcode ']; } ?>' placeholder='postcode'></td>
</div>
<div class="form-group text-left mt-20">
<button type="update" class="btn btn-primary pull-right" name="update" id='update'>Add Access</button>
<!-- <label class="checkbox checkbox-custom-alt checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label> -->
<a href="access.php">
<button type="button" class="btn btn-greensea b-0 br-2 mr-5">Back</button>
</a>
</div>
</form>
</div>
<!-- end of container -->
Thanks guy's for requesting for more code... i hope have given enough code sample.
you most put your id inside of a hidden input in your html form like this:
<input type="hidden" name="itemId" value="<?php echo '$_GET['id']'?>">
and then when you submit your form you have itemId in side $_POST['itemId'] variable.
EDIT:
I must describe scenario for you. maybe you got the point.
you have a list of access witch in every row has this tag:
access ....
in your access-form.php you have a form with this structure:
<form method="post" action="edit-access.php">
.....
<input type="hidden" name="id" value="<?php echo $_GET['id']?>">
.....
</form>
next in your edit-access.php you can access to this id by this syntax:
echo $_POST['id'];

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.

PDO says it updates the table, but it actually doesn't

I'm trying to use a form to update a sql table by first getting its data (editrower.php) and setting that as values in the form, then using the form to update the table (update_contactrequest.php) but it returns saying the rower was updated yet the table does not update.
editrower.php
<?php
require('login.php');
?>
<?php
include 'php/mysql_connect.php';
if(isset($_GET['id'])){
$q = $db->prepare('SELECT * FROM rowercontacts WHERE id=:id LIMIT 1');
$q->execute(array(':id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_ASSOC);
if($row){
echo '
<form method="post" action="php/update_contactrequest.php"><div class="col-xs-9 col-md-6 col-lg-6">
<div class="form-group">
<input type="hidden" name="id" id="id" value="'.$_GET['id'].'">
<label for="firstname">First Name</label>
<input type"text" class="form-control" name="firstname" placeholder="First Name" value="'.$row['firstname'].'" />
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name" value="'.$row['lastname'].'" />
</div>
<br><br>
<br><br>
<input type="submit" class="btn btn-default" value="Update" />
</div></form>
';
}
else{
echo 'No rower found';
}
}
else{
echo 'No rower found';
}
?>
update_contactrequest.php:
<?php
session_start();
if($_SESSION['loggedIn'] == true){
$rower_id= $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=home','username','password');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// insert the records
$sql = "UPDATE rowercontacts SET firstname=:firstname, lastname=:lastname WHERE id=:rower_id";
$q = $bdd->prepare($sql);
if($q->execute(array(':firstname'=>$firstname, ':lastname'=>$lastname, ':rower_id'=>$id))){
echo '<script type="text/javascript">alert("Rower Updated.");location.href="../rowerlist.php";</script>';
}
else{
echo '<script type="text/javascript">alert("Something went wrong...");location.href="../rowerlist.php";</script>';
}
}
?>
With $q->rowCount(). Prepared statements will return the number of affected rows.
If the query itself is error free and executes fine, you need the affected rows.
$q = $bdd->prepare($sql);
if($q->execute(array(':firstname'=>$firstname, '...'))){
$updRows = $q->rowCount();
if($updRows==0){
echo '<script type="text/javascript">alert("Affected Rows = 0 !!!");location.href="../rowerlist.php";</script>';
}
else{
echo '<script type="text/javascript">alert("Rows affected : '.$updRows.'");location.href="../rowerlist.php";</script>';
}
}
else{
echo '<script type="text/javascript">alert("Something went wrong...");location.href="../rowerlist.php";</script>';
}
Over 70% of update queries with 0 affected rows are due to an incorrect WHERE the rest comes from the attempt to replace a record with exactly the same values that already exist.
The first thing I do in such a case, I let my query as readable text display.
With $q->debugDumpParams(); you get that query array.
WHERE id = null is usually not what anyone expected.
To your problem I'm sure you can find the wrong part yourself in following 3 lines . :-)
$rower_id= $_POST['id'];
....
$sql = "UPDATE rowercontacts ... WHERE id=:rower_id";
if($q->execute(array(':firstname'=>$firstname,...,':rower_id'=>$id)))

Categories