This question already has answers here:
PHP PDOException: "SQLSTATE[HY093]: Invalid parameter number"
(4 answers)
Closed last month.
I was working on an edit user page and this error appeared:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match the number of tokens in C:\Program Files\xampp\htdocs\ecommerce\admin\members.php:115 Stack trace: #0 C:\Program Files\xampp\htdocs\ecommerce\admin\members.php(115): PDOStatement->execute(Array) #1 {main} thrown in C:\Program Files\xampp\htdocs\ecommerce\admin\members.php on line 115
<?php
/*
manage members page
*/
session_start();
$pageTitle = 'Members';
if (isset($_SESSION['Username'])) {
include 'init.php';
$do = isset($_GET['do']) ? $_GET['do'] : 'manage';
//start manage page
if ($do == 'Manage') {
} elseif ($do == 'Edit') { //edit page
$userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0;
$stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1");
$stmt->execute(array($userid));
$row = $stmt->fetch();
$count = $stmt->rowCount();
if ($stmt->rowCount() > 0) {
?>
<h1 class="text-center">
Edit Member
</h1>
<div class="container">
<form class="form-horizontal" action="?do=Update" method="POST">
<input type="hidden" name="userid" value="<?php echo $userid ?>">
<div class="form-group-lg">
<label for="" class="col-sm-2 control-label">username</label>
<div class="col-sm-10 col-md-4 ">
<input type="text" name="username" value="<?php echo $row['Username'] ?>" class="form-control" autocomplete="off">
</div>
</div>
<div class="form-group-lg">
<label for="" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10 col-md-4 ">
<input name="newpassword" type="hidden" value="<?php echo $row['Password'] ?>">
<input name="oldpassword" type="password" class="form-control" autocomplete="new-password">
</div>
</div>
<div class="form-group-lg">
<label for="" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10 col-md-4 ">
<input type="email" name="email" value="<?php echo $row['Email'] ?>" class="form-control">
</div>
</div>
<div class="form-group-lg">
<label for="" class="col-sm-2 control-label">Full name</label>
<div class="col-sm-10 col-md-4 ">
<input type="text" name="full" value="<?php echo $row['FullName'] ?>" class="form-control">
</div>
</div>
<div class="form-group-lg">
<div class="col-sm-offset-2 col-sm-10 col-md-4 ">
<input type="submit" name="submit" value="Save" class="btn-lg btn-primary ">
</div>
</div>
</form>
</div>
<?php
} else {
echo 'theres no such id';
}
} else if ($do == 'Update') {
echo "<h1 class='text-center'>Update Member</h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['userid'];
$user = $_POST['username'];
$email = $_POST['email'];
$name = $_POST['full'];
//password trick
//condition ? true : false;
$pass = empty($_POST['newpassword']) ? $_POST['oldpassword'] : sha1($_POST['newpassword']);
// validate the form
$formErrors = array();
if(strlen($user) < 4) {
$formErrors[] = '<div class="alert alert-danger">username cant be less than <strong>4 characters</strong></div>';
}
if(strlen($user) > 20) {
$formErrors[] = '<div class="alert alert-danger">username cant be more than <strong>20 characters</strong></div>';
}
if(empty($user)) {
$formErrors[] = '<div class="alert alert-danger">username cant be <strong>empty</strong></div>';
}
if(empty($name)) {
$formErrors[] = '<div class="alert alert-danger">fullname cant be <strong>empty</strong></div>';
}
if(empty($email)) {
$formErrors[] = '<div class="alert alert-danger">email cant be <strong>empty</strong></div>';
}
foreach($formErrors as $error) {
echo $error;
}
//check if there is no errors proceed the update operation
if(empty($formErrors)) {
//update the database
$stmt = $con->prepare("UPDATE users SET Username = ?, Email = ?, FullName = ? WHERE UserID = ?");
$stmt->execute(array($user, $email, $name, $pass, $id));
//echo success message
echo "<div class='alert alert-success'>$stmt->rowCount() . ' Record updated'</div>";
}
} else {
echo 'sorry you cant browse this page directly';
}
echo "</div>";
}
} else {
header('Location: index.php');
exit();
}
$stmt = $con->prepare("UPDATE users SET Username = ?, Email = ?, FullName = ? WHERE UserID = ?");
$stmt->execute(array($user, $email, $name, $pass, $id));
You are missing Password field in your update query. Or remove $pass from the execute array. The count of the arguments are mismatching
Related
This question already has answers here:
Why would $_FILES be empty when uploading files to PHP?
(22 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
I want to insert some data using PHP 7.2 table name seller_login and field user_id, username, password, type_login, image, logo PHP insert in a script. not working. always logo and image about error show please help me
show error here
Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94
Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94
Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95
Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95
PHP code line number like 94
move_uploaded_file($_FILES["logo"]
["tmp_name"],"../sellerimage/$user_id/".$_FILES["logo"]["name"]);
PHP code line number like 95
move_uploaded_file($_FILES["image"]
["tmp_name"],"../sellerimage/$user_id/".$_FILES["image"]["name"]);
PHP all script here
<?php
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
$type_login = $type_err = $type_login = "";
$logo = $logo_err = $logo='';
$image = $image_err = $image='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
$sql = "SELECT user_id FROM seller_login WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = trim($_POST["username"]);
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
//------------------------
if(empty(trim($_POST["type_login"]))){
$type_err = "Please Select User Type.";
} else{
$type_login = trim($_POST["type_login"]);
}
//------------grant----------------
//------------------------
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
//-------------------seller logo insert------------------------
if(empty($_FILES["logo"]["name"])){$logo_err = "Please Select Logo.";}
else{ $logo =$_FILES["logo"]["name"];}
//-------------------image---------------------------
if(empty($_FILES["image"]["name"])){$image_err = "Please Select image.";}
else{$image =$_FILES["image"]["name"];}
//--------------------directory creation for Seller images---------------
$query=mysqli_query($conn,"select max(user_id) as pid from seller_login");
$result=mysqli_fetch_array($query);
$sellerid=$result['pid']+1;
$dir="../sellerimage/$sellerid";
mkdir($dir);// directory creation for Seller images
move_uploaded_file($_FILES["logo"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["logo"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["image"]["name"]);
//----------------------------------------------------------------
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
$sql = "INSERT INTO seller_login (username, password, type_login, logo, image) VALUES (?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "sssss", $param_username, $param_password, $type_login, $logo, $image);
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);
if(mysqli_stmt_execute($stmt)){
$msg="Successfully Login";
} else{
$msg="Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}
?>
HTML form
<form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="row text-center ">
<div class="col-md-2"></div>
<div class="col-md-8"><h3 class="btn-success p-2">Please fill this form to create an account.</h3></div>
<div class="col-md-2"></div>
</div></br>
<!----------------Username---------------->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2"><b>Username</b></div>
<div class="form-group col-md-3 <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>" offset>
<span class="help-block"style="color: #ff0000;text-align:center;"><?php echo $username_err; ?></span>
</div>
<div class="col-md-2"><b>Password</b></div>
<div class="form-group col-md-3 <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $password_err; ?></span>
</div>
<div class="col-md-1"></div>
</div>
<!-------------Password------------------->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2"><b>Confirm Password</b></div>
<div class="form-group col-md-3 <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $confirm_password_err; ?></span>
</div>
<div class="col-md-2"><b>Select User Type</b></div>
<div class="form-group col-md-3 <?php echo (!empty($type_err)) ? 'has-error' : ''; ?>">
<select name="type_login" class="form-control">
<option value="">Select</option>
<option value="1">Add Seller</option>
</select>
<span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $type_err; ?></span>
</div>
<div class="col-md-1"></div>
</div>
<!------------Select picture------------>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2"><b>Profile Picture</b></div>
<div class="form-group col-md-3 <?php echo (!empty($image_err)) ? 'has-error' : ''; ?>">
<input type="file" name="image" class="form-control p-0" value="<?php echo $image; ?>">
<span class="help-block"style="color: #ff0000;text-align:center;"><?php echo $image_err; ?></span>
</div>
<div class="col-md-2"><b>Company Logo</b></div>
<div class="form-group col-md-3 <?php echo (!empty($logo_err)) ? 'has-error' : ''; ?>">
<input type="file" name="logo" class="form-control p-0" value="<?php echo $logo; ?>">
<span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $logo_err; ?></span>
</div>
<div class="col-md-1"></div>
</div>
<hr><hr>
<!----------------------------->
<div class="row">
<div class="col-md-5"></div>
<div class="form-group col-md-2">
<button type="submit" name="submit" class="btn btn-success"size="40" style="cursor: pointer;">Insert</button>
</div>
<div class="form-group col-md-3">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<div class="col-md-2"></div>
</div>
</form>
Use enctype when u open form (enctype="multipart/form-data):
<form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
I am having two different database tables questions and choices where i am inserting questions in one table and multiple choices in another table where questions table id is foreign key in choices table.
Questions:
Questions_number Text
1 What is HTML?
2 What is PHP?
Choices:
id question_number is_correct text
1 1 1 markup
2 1 0 Hyext
3 1 0 Hyper text markup language
4 2 0 hsdfd
5 2 0 frfwer
6 2 1 Hypertext Preprocessor
If i am trying to edit question number 1 then i need to fetch all the details of questions,Choices and correct option as well.But when i am trying to edit the record for choices as well i am getting the same data which i am getting for question.
HTML:
<?php session_start();
include 'includes/db.php';
$id = (int)$_GET['id'];
$sql = "SELECT * FROM questions q WHERE q.question_number = $id ";
$oppointArr =array();
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result))
{
$oppointArr = $row;
echo "Text: " . $row["text"]. "<br>";
}
} else {
echo "0 results";
}
?>
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<div class="form-group">
<label for="choice #1" class="col-sm-2 control-label">Choice #1</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice1'];?>" name="choice1" id="choice1">
</div>
</div>
<div class="form-group">
<label for="choice #2" class="col-sm-2 control-label">Choice #2</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice2'];?>" name="choice2" id="choice2">
</div>
</div>
<div class="form-group">
<label for="choice #3" class="col-sm-2 control-label">Choice #3</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice3'];?>" name="choice3" id="choice3">
</div>
</div>
<div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['is_correct'];?>" name="is_correct" id="is_correct">
</div>
</div>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
Updatequestions:
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['correct_choice'];
$choices = array();
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$choices[4] = $_POST['choice4'];
$choices[5] = $_POST['choice5'];
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row) {
foreach($choices as $choice => $value){
if($value != ''){
if($correct_choice == $choice){
$is_correct = 1;
} else {
$is_correct = 0;
}
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
}
$msg = 'Question has been added';
}
}
?>
If i try to update the record all the fields are updating with the same data.
WARNING: Do not create SQL statements by concatenating the data with SQL. Use prepared statements.
As for your problem, you use the foreign key of the question to update choices. The key is not the primary key of choices and is not unique. Try using the unique primary key for your SQL.
Instead of this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
try this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE id=$choice ";
But of course you should really try to do it all over again using prepared statements instead!
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<?php
$choicesql = "SELECT * FROM `choices` WHERE question_number = $id ";
$ChoicetArr =array();
$choiceresult = mysqli_query($mysqli,$choicesql);
$inc=1;
$correctAns ="";
if (mysqli_num_rows($choiceresult) > 0)
{
while($rows = mysqli_fetch_array($choiceresult))
{
$ChoicetArr[] = $rows;
?>
<div class="form-group">
<label for="choice #<?php echo $inc;?>" class="col-sm-2 control-label">Choice #<?php echo $inc;?></label>
<div class="col-sm-5">
<input type="hidden" name="choice_id<?php echo $inc;?>" value="<?php echo $rows['id'];?>">
<input type="text" class="form-control" value="<?php echo $rows['text'];?>" name="choice<?php echo $inc;?>" id="choice<?php echo $inc;?>">
</div>
</div>
<?php
//print_r($rows);
if($rows['is_correct']=="1"){
$correctAns = '<input type="hidden" name="choice_id'.$inc.'" value="'.$rows['id'].'"><div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="'.$inc.'" name="is_correct" id="is_correct">
</div>
</div>';
}
$inc++;
}
}
echo $correctAns;
?>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
updatequestions.php
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['is_correct'];
$choices = array();
$choices[] = array("question"=>$_POST['choice1'], "answer"=>$_POST['choice_id1']);
$choices[] = array("question"=>$_POST['choice2'], "answer"=>$_POST['choice_id2']);
$choices[] = array("question"=>$_POST['choice3'], "answer"=>$_POST['choice_id3']);
$choices[] = array("question"=>$_POST['choice4'], "answer"=>$_POST['choice_id4']);
$choices[] = array("question"=>$_POST['choice5'], "answer"=>$_POST['choice_id5']);
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row)
{
$inc= 0;
foreach($choices as $choice => $value){
if(count($value)>0){
$answerInc = $choice+1;
if($correct_choice == $answerInc){
$is_correct = 1;
} else {
$is_correct = 0;
}
$text= $value['question'];
$answer = $value['answer'];
//echo "<br>".$text;
//print_r($value);
echo $answerInc;
echo "<br>";
echo $query = "UPDATE choices SET is_correct='$is_correct', text='$text' WHERE id=$answer";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
$inc++;
}
$msg = 'Question has been Updated Successfully';
header("location:searchquestions.php");
exit;
}
}
?>
I have a table that has "customer registration" "Update Billing Address" and "Update Shipping Address" a group of fields. Upon registration the user fills the "customer registration".
I'd like the values on this field ("customer registration") to be populated automatically on "Update Billing Address" and "Update Shipping Address" instead of filling both fields manually. Note these are different fields but on same table in the Database.
How do I achieve this? Please pardon me if this question is too elementary, I've tried to find the answer here from previous post but can't get what I want. enter image description here
<?php require_once('header.php'); ?>
<?php
// Check if the customer is logged in or not
if(!isset($_SESSION['customer'])) {
header('location: '.BASE_URL.'logout.php');
exit;
} else {
// If customer is logged in, but admin make him inactive, then force logout this user.
$statement = $pdo->prepare("SELECT * FROM tbl_customer WHERE cust_id=? AND cust_status=?");
$statement->execute(array($_SESSION['customer']['cust_id'],0));
$total = $statement->rowCount();
if($total) {
header('location: '.BASE_URL.'logout.php');
exit;
}
}
?>
<?php
if (isset($_POST['form1'])) {
$valid = 1;
if(empty($_POST['cust_name'])) {
$valid = 0;
$error_message .= LANG_VALUE_123."<br>";
}
if(empty($_POST['cust_phone'])) {
$valid = 0;
$error_message .= LANG_VALUE_124."<br>";
}
if(empty($_POST['cust_address'])) {
$valid = 0;
$error_message .= LANG_VALUE_125."<br>";
}
if(empty($_POST['cust_country'])) {
$valid = 0;
$error_message .= LANG_VALUE_126."<br>";
}
if(empty($_POST['cust_city'])) {
$valid = 0;
$error_message .= LANG_VALUE_127."<br>";
}
if(empty($_POST['cust_state'])) {
$valid = 0;
$error_message .= LANG_VALUE_128."<br>";
}
if(empty($_POST['cust_zip'])) {
$valid = 0;
$error_message .= LANG_VALUE_129."<br>";
}
if($valid == 1) {
// update data into the database
$statement = $pdo->prepare("UPDATE tbl_customer SET cust_name=?, cust_cname=?, cust_phone=?, cust_country=?, cust_address=?, cust_city=?, cust_state=?, cust_zip=? WHERE cust_id=?");
$statement->execute(array(
strip_tags($_POST['cust_name']),
strip_tags($_POST['cust_cname']),
strip_tags($_POST['cust_phone']),
strip_tags($_POST['cust_country']),
strip_tags($_POST['cust_address']),
strip_tags($_POST['cust_city']),
strip_tags($_POST['cust_state']),
strip_tags($_POST['cust_zip']),
$_SESSION['customer']['cust_id']
));
$success_message = LANG_VALUE_130;
$_SESSION['customer']['cust_name'] = $_POST['cust_name'];
$_SESSION['customer']['cust_cname'] = $_POST['cust_cname'];
$_SESSION['customer']['cust_phone'] = $_POST['cust_phone'];
$_SESSION['customer']['cust_country'] = $_POST['cust_country'];
$_SESSION['customer']['cust_address'] = $_POST['cust_address'];
$_SESSION['customer']['cust_city'] = $_POST['cust_city'];
$_SESSION['customer']['cust_state'] = $_POST['cust_state'];
$_SESSION['customer']['cust_zip'] = $_POST['cust_zip'];
}
}
?>
<div class="page">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php require_once('customer-sidebar.php'); ?>
</div>
<div class="col-md-12">
<div class="user-content">
<h3>
<?php echo LANG_VALUE_117; ?>
</h3>
<?php
if($error_message != '') {
echo "<div class='error' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$error_message."</div>";
}
if($success_message != '') {
echo "<div class='success' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$success_message."</div>";
}
?>
<form action="" method="post">
<?php $csrf->echoInputField(); ?>
<div class="row">
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_102; ?> *</label>
<input type="text" class="form-control" name="cust_name" value="<?php echo $_SESSION['customer']['cust_name']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_103; ?></label>
<input type="text" class="form-control" name="cust_cname" value="<?php echo $_SESSION['customer']['cust_cname']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_94; ?> *</label>
<input type="text" class="form-control" name="" value="<?php echo $_SESSION['customer']['cust_email']; ?>" disabled>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_104; ?> *</label>
<input type="text" class="form-control" name="cust_phone" value="<?php echo $_SESSION['customer']['cust_phone']; ?>">
</div>
<div class="col-md-12 form-group">
<label for=""><?php echo LANG_VALUE_105; ?> *</label>
<textarea name="cust_address" class="form-control" cols="30" rows="10" style="height:70px;"><?php echo $_SESSION['customer']['cust_address']; ?></textarea>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_106; ?> *</label>
<select name="cust_country" class="form-control">
<?php
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
?>
<option value="<?php echo $row['country_id']; ?>" <?php if($row['country_id'] == $_SESSION['customer']['cust_country']) {echo 'selected';} ?>><?php echo $row['country_name']; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_107; ?> *</label>
<input type="text" class="form-control" name="cust_city" value="<?php echo $_SESSION['customer']['cust_city']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_108; ?> *</label>
<input type="text" class="form-control" name="cust_state" value="<?php echo $_SESSION['customer']['cust_state']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_109; ?> *</label>
<input type="text" class="form-control" name="cust_zip" value="<?php echo $_SESSION['customer']['cust_zip']; ?>">
</div>
</div>
<input type="submit" class="btn btn-primary" value="<?php echo LANG_VALUE_5; ?>" name="form1">
</form>
</div>
</div>
</div>
</div>
</div>
I expect the value of the cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip to populate on the equivalent fields. If you understand what I mean.
The answear is in your code:
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){ }?>
The last foreach is a cicle it runs on all the result table, so if you want to update the filds, you need to change the "question" to the table you want to query and then on the cicle store them in the correct variables cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip i suppose.
Good Luck
I have a page to add new users to the MySQL with PHP. And the problem with this is, that it sets id of a new user to 0 whenever it runs. So I don't want that.. I want it to start from id of 1 and if it exists in table, try more than that like 2 for example.
I don't think for this example, you won't need to look at my php files but if you do, here you can see the admin_new.php:
<?php
$notice = array();
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Main Admin"){
$level = 1;
}else if($groups == "Administrator"){
$level = 2;
}else if($groups == "Content Creator"){
$level = 3;
}else if($groups == "Social Media Manager"){
$level = 4;
}else{
$level = 5;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$registration->CheckUname($username,$email,$password,$groups,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<?php
if(isset($notice['validation_email'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['validation_email'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<section class="content">
<div class="row">
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<form role="form" method="POST" action="">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Main Admin">Main Admin</option>
<option value="Administrator">Administrator</option>
<option value="Content Creator">Content Creator</option>
<option value="Social Media Manager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin types documentation to know the differences between each admin.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
And here is the class that I have used which is called Register.class.php:
<?php
class Register
{
private $db;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&($email))
{
$chk1 = $this->db->prepare("SELECT username FROM admins WHERE user_name= ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $notice;
}else{
$chk2 = $this->db->prepare("SELECT email FROM admins WHERE email_address= ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
}
?>
Run this commend on mysql terminal:
ALTER TABLE tablename MODIFY COLUMN id INT auto_increment PRIMARY KEY
the above command will make the id an auto_increment as well as primary key. So for every value you insert, auto_increment will generate a new value for column id, you don't have to assign some value in it.
Last Week working all correctly but today i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''Mees'')' at line 1' in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php:47 Stack trace: #0 /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php(47): PDOStatement->execute(Array) #1 {main} thrown in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php on line 47
PHP Code here
<?php
require 'conf/db.php';
if ( !empty($_POST)) {
// keep track validation errors
$nimiError = null;
$emailError = null;
$mobiilError = null;
$suguError = null;
// keep track post values
$nimi = $_POST['nimi'];
$email = $_POST['email'];
$mobiil = $_POST['mobiil'];
$sugu = $_POST['sugu'];
// validate input
$valid = true;
if (empty($nimi)) {
$nimiError = 'Palun sisesta nimi';
$valid = false;
}
if (empty($email)) {
$emailError = 'Palun sisesta e-mail';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Palun sisesta korrektne e-mail';
$valid = false;
}
if (empty($mobiil)) {
$mobiilError = 'Palun sisesta mobiili number';
$valid = false;
}
if (empty($sugu)) {
$suguError = 'Palun vali sugu';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu) values(?, ?, ?, ?')";
$q = $pdo->prepare($sql);
$q->execute(array($nimi,$email,$mobiil,$sugu));
Database::disconnect();
header("Location: index.php");
}
}
?>
<!DOCTYPE html>
<html lang="et">
<head>
<meta charset="utf-8">
<title>Klientide andmed by Siim Aarmaa IS-13</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<div class="row">
<h3>Lisa uus klient</h3>
</div>
<form class="form-horizontal" action="lisa.php" method="post">
<div class="form-group <?php echo !empty($nimiError)?'error':'';?>">
<label class="col-sm-2 control-label">Nimi</label>
<div class="controls">
<input name="nimi" type="text" placeholder="Nimi" value="<?php echo !empty($nimi)?$nimi:'';?>">
<?php if (!empty($nimiError)): ?>
<span class="help-block"><?php echo $nimiError;?></span>
<?php endif; ?>
</div>
</div>
<div class="form-group <?php echo !empty($emailError)?'error':'';?>">
<label class="col-sm-2 control-label">E-mail</label>
<div class="controls">
<input name="email" type="text" placeholder="E-mail" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-block"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($mobiilError)?'error':'';?>">
<label class="col-sm-2 control-label">Mobiili number</label>
<div class="controls">
<input name="mobiil" type="text" placeholder="Mobiili number" value="<?php echo !empty($mobiil)?$mobiil:'';?>">
<?php if (!empty($mobiilError)): ?>
<span class="help-block"><?php echo $mobiilError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($suguError)?'error':'';?>">
<label class="col-sm-2 control-label">Sugu</label>
<div class="controls">
<input name="sugu" type="radio" value="<?php echo !empty($mees)?$mees:'Mees';?>">Mees
<input name="sugu" type="radio" value="<?php echo !empty($naine)?$naine:'Naine';?>">Naine
<?php if (!empty($suguError)): ?>
<span class="help-block"><?php echo $suguError;?></span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Lisa klient</button>
<a class="btn btn-default" href="index.php">Tagasi</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>`enter code here`
You have a syntax error, a exta single quote in your query:
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu) values(?, ?, ?, ?')";
^
Change it to:
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu) values(?, ?, ?, ?)";