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();
}
}
Related
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.
I am working on a class project, but I am stuck a little bit.
I am working on a login form, which authorizes a user to enter a one-time-password that is being sent to the user's email.
So far, the otp and the current time and date are being saved to the database successfully.
I have also managed to send the code to the user's email but once it is sent, the page does not navigate to the form where the user is supposed to enter the one-time-password.
All that works is this part here:
<form method="post" action="">
.
.
.
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
.
.
.
</form>
What could be the problem?? Can someone please help me on this.Thank you.
Here is the html part:
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top" role="navigation" style="margin-bottom:20px">
<div class="navbar-header">
<a class="navbar-inverse" href="http://localhost/Dreamweaver/index.php"><img src="img/neza.png" alt="logo"></a>
</div>
<!-- /.navbar-header -->
</nav>
</div>
<div class="container">
<div class="card card-container">
<form class="form-signin" method="post" action="">
<?php
if($success == 1) {
?>
<div class="form-wrap">
<h2>A verification code has been sent to <?php $row["form_email"] ?>. Please enter it below to verify your account.</h2>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<div class="form-group">
<label for="key">Verification Code:</label>
<input type="password" name="otp" id="key" class="form-control">
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" name="submit_otp" value="Verify Account">
<h2>Did not receive the verification code?</h2>
<!---- <form id="login-form"> ------>
<input type="submit" id="btn-login" class="btn btn-custom1 btn-lg btn-block" value="Resend Code">
<!----- </form> ----->
</div> <!---/form-wrap----->
<?php
} elseif ($success == 2) {
header("Location: fomu.php");
}else {
?>
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
</form>
<?php
}
?>
</form>
</div><!-- /card-container -->
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="text-centre">
<a class="text-new" href="#">Privacy|</a>
<a class="text-new" href="#">Security|</a>
<a class="text-new" href="#">Fees</a>
</div>
</div> <!---/row--->
</div> <!---/container--->
</div><!-- /container1-->
<!-- jQuery -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="logwin.js"></script>
<script src="bootstrap.min.js"></script>
<script src="js/mscript.js"></script>
<script src="js/scripts.js"></script>
<script src="js/jquery.backstretch.min.js"></script>
</body>
</html>
Here is the dbtest.php used to INSERT TO the db:
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "myPassword";
private $database = "myDB";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function generate_OTP($length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789'){
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
for ($i = 1; $i < $length; $i = strlen($string)){
$r = $chars{rand(0, $chars_length)};
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
function getConn(){
return $this->conn;
}
}
?>
Here is the PHP code that I am referring to:
<?php
session_start();
$success = "";
require_once('dbtest.php');
$db = new DBController();
if(isset($_POST["login"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE
form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
if (!empty($result)){
foreach($result as $row){
//Verify password
if ( $row['form_password'] === crypt( $_POST["form_password"], $row['form_password'] ) ) {
$otp = $db->generate_OTP();
require_once("mail_function.php");
$mail_status = sendOTP($_POST["form_email"],$otp);
if($mail_status == 1) {
$query = "UPDATE registered_users SET `otp` = '" . $otp . "', `is_expired` = 0, `create_at` = '" . date("Y-m-d H:i:s"). "' WHERE form_email = '" . $_POST["form_email"] . "'";
$result = $db->updateQuery($query);
if(!empty($result)){
$current_id = mysqli_insert_id($db->getConn());
if(!empty($current_id)) {
$success = 1;
}
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
if(isset($_POST["submit_otp"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");
if(!empty($result)) {
$query = "UPDATE registered_users SET `is_expired` = 1 WHERE otp = '" . $_POST["otp"] . "'";
$result = $db->updateQuery($query);
$success = 2;
}else {
$success = 1;
$error_message = "Invalid OTP!";
}
}
?>
Bad syntax: you have the <html> tag inside the <form>, that should not happen. The <html> should only be used once at the beginning to open it and end at the end to close it.
UPDATE:
Also, mysqli_insert_id() expects the link identifier of the last mysqli_connect used. In your code, youre supplying it with $conn, but $conn is not whats being used in the DBController class.
To fix this:
add this method to you DBController class:
function getConn(){
return $this->conn;
}
then change this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($conn);
if (!empty($current_id)) {
$success = 1;
}
}
to this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($db_handle->getConn());
if (!empty($current_id)) {
$success = 1;
}
}
UPDATE2:
You asked this "After adding this method function getConn(){ return $this->conn; } I find some errors working with mysqli_fetch_array(). I am using if(!empty($result->num_rows)){while($rowcount = $result->fetch_assoc()){$row['password'];}}"
look at what runQuery() does:
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
it runs your SQL query, then if there are any results, it returns an array $resultset.. The problem is that you are not accounting for empty results. So lets add that, change it to this:
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
Now it will return an empty array, or an array with your results.
And you can call it with:
$result = $db->runQuery("SELECT * FROM registered_users WHERE form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
and use $result like this:
if(!empty($result)){
foreach($result as $row){
echo $row['password'];
}
}
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!
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'];
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'];