php echo listbox value from databasebase - php

I have 2 tables
TABLE joke (id, joke_text, joke_date, author_id)
TABLE author(id, name, email)
I am having a problem in echoing the value inserted within author_id field in the list box:
<?php
# display all php errors
error_reporting(-1);
ini_set('display_errors', 1);
# include dbConnection details
require '../includes/dbconn.php';
# initially set $id to empty
$id = null;
# if $id is not empty, GET the id
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
# if $id is empty then send the user back to index.php
if ( null==$id ) {
header("Location: index.php");
exit();
}
if ( !empty($_POST)) {
// keep track validation errors
$joke_textError = null;
$authorError = null;
// keep track post values
$joke_text = $_POST['joke_text'];
$author_id = $_POST['author_id'];
// validate input
$valid = true;
if (empty($joke_text)) {
$joke_textError = 'Please enter joke text';
$valid = false;
}
// update data
if ($valid) {
$sql = "UPDATE joke set joke_text = ?, author_id = ? WHERE id = ?";
$update = $dbConnection->prepare($sql);
$update->execute(array($joke_text,$author_id,$id));
header("Location: index.php");
exit();
}
} else {
$sql = "SELECT joke.id, joke.joke_text, joke.joke_date, author.name, author.email, joke.author_id, author.id
FROM joke INNER JOIN author
ON author_id = author.id
WHERE joke.id = ?";
$select = $dbConnection->prepare($sql);
$select->execute(array($id));
$data = $select->fetch();
$joke_id = $data['id'];
$joke_text = $data['joke_text'];
$joke_date = $data['joke_date'];
$author_name = $data['name'];
$author_email = $data['email'];
$author_id = $data['author_id'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Update Author</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../includes/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<h1>Update Author</h1>
</div>
<form action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php if (!empty($nameError)){ echo 'error';}?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="joke_text" type="text" placeholder="joke text" value="<?php if (!empty($joke_text)){ echo htmlspecialchars(trim($joke_text)); } ?>">
<?php if (!empty($joke_textError)) {
echo '<span class="help-inline">' . $joke_textError . '</span>';
} ?>
</div>
</div>
<select name="author_id" id="author_id">
<option value="">Select one</option>
<?php
$sql2 = 'SELECT id, name FROM author';
foreach ($dbConnection->query($sql2) as $data2) { ?>
<option value="<?php echo $data2['id']; ?>"
<?php if(isset($_POST['author_id']) && $_POST['author_id'] == $data['author_id']) { echo 'selected'; } ?>>
<?php echo htmlspecialchars($data2['name'], ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php } ?>
</select>
<div class="form-actions">
<button type="submit" class="btn btn-green">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</body>
</html>
The data updates into the database just fine, can not figure how to echo it back out into the author_id listbox. If someone could kindly give some assistance it would be great!

Related

Togle to edit Mysql data from PHP

I have a table in my php where I show data from my 'users' table of mysql. In the table I added an edit button so that, if you click on the button, a form is shown below the table where you can edit some fields of the table's content, I have also added a delete button next to it to delete the row of the table you want, but that button works correctly.
The problem I have is with the edit button, which, when pressed, it doesn’t show me the form that I added below the table, but it takes me to the page 'registerTeacher.php?edit = 3' for example. Pressing the 'Edit' button, it should show the form to be able to edit but it doesn’t do anything, nor does it show me any errors. Can someone help me find where the problem is? Thank you.
This is my ‘indexAdmin.php’ code:
<?php
include('server.php');
include('Security.php');
include('Conexion.php');
include('registerTeacher.php');
?>
<?php
$style = "style='display:none;'";
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="styleIndexAdmin.css">
<meta charset="utf-8">
</head>
<body>
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<div class="navbar" id="navbar">
<a class="tablink" onclick="openPage('professorsRegistered', this, 'lightblue')" id="defaultOpen">Profesores</a>
</div>
<!----------- PROFESSROS REGISTERED TABLE ----------->
<div id="professorsRegistered" class="tabcontent"></br><br>
<table class="professorsRegistered">
<tr>
<th colspan="3"><h2>PROFESSORS REGISTERED</h2></th>
</tr>
<tr>
<th> Name </th>
<th> Edit </th>
<th> Delete </th>
</tr>
<?php
$result = $conn->query($sql);
$sql = "SELECT * FROM users WHERE rol='profesor'";
$result = $conn->query($sql);
if ($result->num_rows==0){
echo 'No professors';
}else{
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["username"]."</td>
<td><a href='registerTeacher.php?edit=".$row["id"]."' class='edit_btn' ><i class='fa fa-pencil-square-o' style='cursor:pointer;'></i></a></td>
<td><a class='eliminate' onClick=\"javascript: return confirm('Confirm to delete');\" href=\"deleteTeacher.php?id=".$row['id']."\">X</a></td>
</tr>";
}
}
?>
</table><br><br>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="registerTeacher.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
</div>
<?php endif ?>
<script>
function getUrlVars(){
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
vars[key] =value;
});
return vars;
}
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
p = getUrlVars()["page"];
//alert(p);
if (p==undefined){
document.getElementById("defaultOpen").click();
}else{
openPage(p, this, 'lightblue');
}
</script>
</body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
</html>
This is my ‘registerTeacher.php’ file:
<?php
include('Conexion.php');
$username = "";
$email = "";
$errors = array();
$id = 0;
$update = false;
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Because <a href=..> is used to redirect to some page in your case ,it is redirecting to registerTeacher.phppage as you have specify in your href attribute.Instead you can do like below :
When below <a href..> is clicked you can put form on registerTeacher.php like below :
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="abcpage.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
Then you can passed this details to your action="abcpage.php".and write like below in that page i.e :
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Hope this helps !
Note : Also try using prepared statement it is safe an secure.

How to solve the issue of getting only the last row update?

I'm trying to update multiple row into the database but everytime it could just update only the fourth row which is the $anstext4. What could be the error from this ?
PHP code:
<?php
$_POST = array(); //workaround for broken PHPstorm
parse_str(file_get_contents('php://input'), $_POST);
session_start();
if(isset($_SESSION['doctor'])) {
require 'dbConn.php';
$id = null;
if(!empty($_GET['id'])) {
$questionid = $_REQUEST['id'];
}
if(null==$questionid) {
header("location: admin_home.php");
}
if(!empty($_POST)) {
$questiontextError = null;
$anstext1Error = null;
$anstext2Error = null;
$anstext3Error = null;
$anstext4Error = null;
$questiontext = $_POST['questiontext'];
$anstext1 = $_POST['ans1'];
$anstext2 = $_POST['ans2'];
$anstext3 = $_POST['ans3'];
$anstext4 = $_POST['ans4'];
//$answers = $_POST['ans'];
//$answers = array($_POST['ans1'], $_POST['ans2'], $_POST['ans3'], $_POST['ans4']);
//$answers = array($_POST['ans']);
/*$answers[] = $_POST['ans1'];
$answers[] = $_POST['ans2'];
$answers[] = $_POST['ans3'];
$answers[] = $_POST['ans4'];*/
$radiobtn = $_POST['radioans'];
$valid = true;
if(empty($questiontext)) {
$questiontextError = 'Please enter valid data';
$valid = false;
}
/* if(empty($anstext1)) {
$anstext1Error = 'Enter the first data';
$valid = false;
}
if(empty($anstext2)) {
$anstext2Error = 'Enter the second data';
$valid = false;
}
if(empty($anstext3)) {
$anstext3Error = 'Enter the third data';
$valid = false;
}
if(empty($anstext4)) {
$anstext4Error = 'Enter the fourth data';
$valid = false;
}*/
//Update the data
if($valid) {
$sql = "UPDATE `question`
SET `question_text` = :questiontext,
`question_type` = 'mcq',
`correct_answer` = :radioans
WHERE question.id = ".$questionid;
//$result = $conn->query($sql);
$result = $conn->prepare($sql);
$result->bindParam(":questiontext", $questiontext);
$result->bindParam(":radioans", $radiobtn);
//$result->execute(array($questiontext,$radiobtn));
$result->execute();
// $count= null;
/*for($i=0; $i<$count; $i++) {
$sql2 = "UPDATE `option_tbl` SET option_answer=':ans[$i]' WHERE question_id = ".$questionid;
$result2 = $conn->prepare($sql2);
$result2->execute();
}*/
/*$sql2 = "UPDATE `option_tbl`
SET `option_answer` = :ans
WHERE question_id = ".$questionid;
$result2 = $conn->prepare($sql2);*/
$sql2 = "UPDATE `option_tbl`
SET `option_answer` = :ans
WHERE question_id = '$questionid'";
$result2 = $conn->prepare($sql2);
$result2->bindParam(":ans",$anstext1);
$result2->execute();
$result2->bindParam(":ans",$anstext2);
$result2->execute();
$result2->bindParam(":ans",$anstext3);
$result2->execute();
$result2->bindParam(":ans",$anstext4);
$result2->execute();
//$result2->bindParam(":ans", $answers);
$result2->execute();
/*$result2->execute(array(":ans" => $_POST['ans1'],
":ans" => $_POST['ans2'],
":ans" => $_POST['ans3'],
":ans" => $_POST['ans4']));*/
/*for($i=0; $i < count($questionid); $i++) {
$result2->execute([
':ans' => $_POST['ans1'][$i],
':ans' => $_POST['ans2'][$i],
':ans' => $_POST['ans3'][$i],
':ans' => $_POST['ans4'][$i]]);
print_r($result2);
}*/
/*foreach ($answers as $answer) {
$result2 = $conn->prepare("UPDATE `option_tbl` SET `option_answer` =? WHERE question_id =?");
$result2->bindParam("ss", $answer, $questionid);
$result2->execute();
}*/
/*$sql2 = "UPDATE `option_tbl` SET `option_answer` = :ans WHERE '$questionid' = :id";
foreach ($answers as $key => $answer) {
$result2 = $conn->prepare($sql2);
$result2->bindParam(':ans', $answer);
//$result2->bindParam(':id', $questionid);
$result2->execute();
}*/
$conn = null;
//header('Location: '.$_SERVER['PHP_SELF']);
echo "Successful";
}
}
?>
Both of the answer will affect the whole column result it to be the last values.
HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Assets/index_style.css"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css"/>
<link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">
<script src="Assets/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
//back button function
function goBack() {
window.history.back();
}
</script>
</head>
<body>
<div class="container">
<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active">Settings</li>
<li role="presentation">Logout</li>
</ul>
</nav>
</div> <!-- /container -->
<div class="container">
<button type="button" class="btn btn-success" onclick="goBack()">back</button>
<br>
<h3 class="text-muted">Update the data</h3>
<div class="span10 offset1">
<form class="form-horizontal" action="admin_update.php?id=<?php echo $questionid?>" method="POST">
<div class="control-group <?php echo !empty($questiontextError)?'error':'';?>">
<label class="control-label">Question: </label>
<div class="controls">
<input name="questiontext" type="text" size="60" placeholder="Question" value="<?php echo !empty($questiontext)?$questiontext:'';?>">
<?php if (!empty($questiontextError)): ?>
<span class="help-inline"><?php echo $questiontextError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($anstext1Error)?'error':'';?>">
<label class="control-label">1.</label>
<!--<div class="controls">-->
<input name="ans1" type="text" size="40" value="<?php echo !empty($anstext1)?$anstext1:'';?>">
<input type="radio" name="radioans" value="1">
<?php if (!empty($anstext1Error)): ?>
<span class="help-inline"><?php echo $anstext1Error;?></span>
<?php endif;?>
<!--</div>-->
</div>
<div class="control-group <?php echo !empty($anstext2Error)?'error':'';?>">
<label class="control-label">2.</label>
<!--<div class="controls">-->
<input name="ans2" type="text" size="40" value="<?php echo !empty($anstext2)?$anstext2:'';?>">
<input type="radio" name="radioans" value="2">
<?php if (!empty($anstext2Error)): ?>
<span class="help-inline"><?php echo $anstext2Error;?></span>
<?php endif;?>
<!--</div>-->
</div>
<div class="control-group <?php echo !empty($anstext3Error)?'error':'';?>">
<label class="control-label">3.</label>
<!--<div class="controls">-->
<input name="ans3" type="text" size="40" value="<?php echo !empty($anstext3)?$anstext3:'';?>">
<input type="radio" name="radioans" value="3">
<?php if (!empty($anstext3Error)): ?>
<span class="help-inline"><?php echo $anstext3Error;?></span>
<?php endif;?>
<!--</div>-->
</div>
<div class="control-group <?php echo !empty($anstext4Error)?'error':'';?>">
<label class="control-label">4.</label>
<!--<div class="controls">-->
<input name="ans4" type="text" size="40" value="<?php echo !empty($anstext4)?$anstext4:'';?>">
<input type="radio" name="radioans" value="4">
<?php if (!empty($anstext4Error)): ?>
<span class="help-inline"><?php echo $anstext4Error;?></span>
<?php endif;?>
<!--</div>-->
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="crud.php">Back</a>
</div>
</form>
</div>
</div>
<footer class="footer">
<p>© 2016, Inc.</p>
</footer>
</body>
</html>
<?php
}
?>
I tried using foreach but it won't work
foreach ($answers as $answer) {
$stmt = $conn->prepare("UPDATE option_tbl SET option_answer = :ans
WHERE question_id = '$questionid'");
$stmt->execute();
}
Make a foreach loop to update with each of the binding parameters. You are setting 4 values to one parameter, that's why it's takes the last one. You need a loop
Try this:
if (!empty($_POST)) {
$answers = array($_POST['ans1'], $_POST['ans2'], $_POST['ans3'], $_POST['ans4']);
foreach ($answers as $answer) {
$result = $conn->prepare("UPDATE option_tbl SET option_answer =? WHERE question_id =?");
$result->bindParam("ss", $answer, $questionid);
$result->execute();
}
}
First you need to know that you to make seprade call for each query so you need to make a 'prepare' call for evry call
(there is a way to make it in one call, but we leave it for now)
so
if(!empty($_POST)){
$answers = $_POST // duplicate _POST array into answers
// Declering the sql template, pay attenion that I make another param to bind in, :id
$sql = "UPDATE `option_tbl` SET `option_answer` = :ans WHERE question_id = :id";
// Then for each on answers array
foreach ($answers as $key => $answer) {
// prepare
$result = $conn->prepare($sql);
// bind the params
$result->bindParam(':ans', $answer);
$result->bindParam(':id', $YourId); // Best want is to do array of ids and bind the $key of the foreach in it
// Execute the query
$result->execute();
}
}

Customized validation messages not working?

Am trying to add custom validation messages to this form, but cannot figure it out for the life of me..
Any help/advice is appreciated...thank you.
I have tried a few tutorials, but nothing seems to be clicking for me, I am sure its something simple, but I just cant seem to figure it out.
Thanks
FORM FOR THE VALIDATION:
<?php
if (isset($_POST['insert'])) {
require_once('connection.php');
$OK = false;
$sql = 'INSERT INTO students (studentTitle, studentFirstName, studentLastName)
VALUES(:studentTitle, :studentFirstName, :studentLastName)';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':studentTitle', $_POST['studentTitle'], PDO::PARAM_STR);
$stmt->bindParam(':studentFirstName', $_POST['studentFirstName'], PDO::PARAM_STR);
$stmt->bindParam(':studentLastName', $_POST['studentLastName'], PDO::PARAM_STR);
$stmt->execute();
$OK = $stmt->rowCount();
if ($OK) {
header('Location: http://localhost/mysqlquiz/student.php');
exit;
} else {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Add Student Details</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="header">New student details</h1>
<p>Student Listing </p>
<?php
if (isset($error)) {
echo "<p class='warning'>Error: $error</p>";
}
?>
<?php
// define variables and set to empty values
$studentTitleErr = $studentFirstNameErr = $studentLastNameErr = "";
$studentTitle = $studentFirstName = $studentLastName = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["studentTitle"])) {
$studentTitleErr = "A title is required";
} else {
$studentTitle = test_input($_POST["studentTitle"]);
}
if (empty($_POST["studentFirstName"])) {
$studentFirstNameErr = "First name is required";
} else {
$studentFirstName = test_input($_POST["studentFirstName"]);
}
if (empty($_POST["studentLastName"])) {
$studentLastNameErr = "Last name is required";
} else {
$studentLastName = test_input($_POST["studentLastName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p>
<label for="studentTitle">Title:</label>
<select name="studentTitle" id="studentTitle" ><span class="error">* <?php echo $studentTitleErr;?></span>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss.</option>
</select>
</p>
<p>
<label for="studentFirstName">First Name:</label>
<input type="text" name="studentFirstName" id="studentFirstName" ><span class="error">* <?php echo $studentFirstNameErr;?></span>
</p>
<p>
<label for="studentLastName">Last Name:</label>
<input type="text" name="studentLastName" id="studentLastName" ><span class="error">* <?php echo $studentLastNameErr;?></span>
</p>
<p>
<input type="submit" name="insert" value="Add Details" id="insert">
<input type="reset" name="clear" value="Clear" id="clear">
<input name="studentID" type="hidden" value="<?php echo $studentID; ?>">
</p>
</form>
</body>
</html>
I have updated your code. you should check the validation first then insert.
<?php
// define variables and set to empty values
$studentTitleErr = $studentFirstNameErr = $studentLastNameErr = "";
$studentTitle = $studentFirstName = $studentLastName = "";
if (isset($_POST['insert'])) {
require_once('connection.php');
$error = $OK = false;
if (empty($_POST["studentTitle"])) {
$studentTitleErr = "A title is required";
$error = true;
} else {
$studentTitle = test_input($_POST["studentTitle"]);
}
if (empty($_POST["studentFirstName"])) {
$studentFirstNameErr = "First name is required";
$error = true;
} else {
$studentFirstName = test_input($_POST["studentFirstName"]);
}
if (empty($_POST["studentLastName"])) {
$studentLastNameErr = "Last name is required";
$error = true;
} else {
$studentLastName = test_input($_POST["studentLastName"]);
}
if($error == false)
{
$sql = 'INSERT INTO students (studentTitle, studentFirstName, studentLastName)
VALUES(:studentTitle, :studentFirstName, :studentLastName)';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':studentTitle', $_POST['studentTitle'], PDO::PARAM_STR);
$stmt->bindParam(':studentFirstName', $_POST['studentFirstName'], PDO::PARAM_STR);
$stmt->bindParam(':studentLastName', $_POST['studentLastName'], PDO::PARAM_STR);
$stmt->execute();
$OK = $stmt->rowCount();
if ($OK) {
header('Location: http://localhost/mysqlquiz/student.php');
exit;
} else {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Add Student Details</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="header">New student details</h1>
<p>Student Listing </p>
<?php
if (isset($error)) {
echo "<p class='warning'>Error: $error</p>";
}
?>
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p>
<label for="studentTitle">Title:</label>
<select name="studentTitle" id="studentTitle" ><span class="error">* <?php echo $studentTitleErr;?></span>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss.</option>
</select>
</p>
<p>
<label for="studentFirstName">First Name:</label>
<input type="text" name="studentFirstName" id="studentFirstName" ><span class="error">* <?php echo $studentFirstNameErr;?></span>
</p>
<p>
<label for="studentLastName">Last Name:</label>
<input type="text" name="studentLastName" id="studentLastName" ><span class="error">* <?php echo $studentLastNameErr;?></span>
</p>
<p>
<input type="submit" name="insert" value="Add Details" id="insert">
<input type="reset" name="clear" value="Clear" id="clear">
<input name="studentID" type="hidden" value="<?php echo $studentID; ?>">
</p>
</form>
</body>
</html>
Because your DB insert operation runs first and has no checks for required field data in order to run or not. So, it runs, and on success it redirects and exits:
header('Location: http://localhost/mysqlquiz/student.php');
exit;
Which clears POST and your required field logic never gets run.

PHP MySQL not updating for CRUD app

I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];

Updation not working using pdo in php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Categories