Updating post with PHP & MySQL - php

I'm building a sort of blog system, but I'm having trouble with editing an existing 'post' in the system. It is collecting the data from the database, and it displays it. But when I click the update button, I get this error. I've looked for it, checked my code couple of times, but I just couldn't find anything. This is the error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
And this is my code.
<?php //include config
require_once('../../includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bewerk</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="../style/normalize.css">
<link rel="stylesheet" href="../style/main.css">
<link rel="stylesheet" href="../style/login.css">
</head>
<body>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT patient_id, voornaam, achternaam, leeftijd, lengte, gewicht, foto_url FROM patienten WHERE patient_id = :patient_id') ;
$stmt->execute(array(':patient_id' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare('UPDATE patiënten SET patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
':patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
//redirect to index page
header('Location: index.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<div class="row">
<div class="col-md-2 col-md-offset-5">
<img src="../style/images/logo.png">
</div>
</div>
<div class="keuze_link row">
<p><b><?php echo $row['voornaam'];?> <?php echo $row['achternaam'];?></b> bewerken</p>
</div>
<div class="container">
<form class="toevoegen" action="" method="post">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];? >">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
</div>
</body>
</html>
If you guys wanna know more, or see more code, I'd like to hear it. Thanks in advance.
EDIT. for update.
//insert into database
$stmt = $db->prepare('UPDATE patienten SET patient_id = :patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
'patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
Latest form for update
<form class="toevoegen" action="" method="post">
<input type="hidden" name="voornaam" value="<?php echo $row['patient_id'];?>">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];?>">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>

:patient_id is missing from the $stmt->execute() function. Please add it and try again.

In your update query you forgot about :patient_id to bind
And yes, remove $ before column names.

Related

Displaying input error messages next to the input field

I would like to display error checking next to the input field. Currently, errors are displayed at the top of the page.
Maybe there is some way to check for input errors?
I could not find a similar example where html and php code are separated into different files
Or my code is completely wrong.
index.php
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>testpage</title>
</head>
<body>
<?php
require('process.php');
?>
<h1>Form</h1>
<form method="post" action="">
<div> Date : <input type="date" name="date"/><br />
</div>
<div>
<label>Start:</label>
<select name="starttime" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>End:</label>
<select name="endtime">
<option value="18:00:00">18:00</option>
</select>
<br>
</div>
<div>
Name : <input type="text" name="user_name" placeholder="Name" /><br />
</div>
Mail : <input type="email" name="user_email" placeholder="Mail" /><br />
Message : <textarea name="user_text"></textarea><br />
<input type="submit" value="Send" />
</form>
<h3 class=" txt_center">DB Output <span id="curdate">
<?php require('calendar.php');
?>
<!-- <script type="text/javascript" src="js/time-select.js"></script> -->
</body>
</html>
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
$u_starttime = $_POST["starttime"];
$u_endtime = $_POST["endtime"];
$u_name = filter_var($_POST["user_name"]);
$u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$u_text = filter_var($_POST["user_text"]);
$error = array();
if (empty($u_date)){
$error['date'] = 'Date is empty!';
}
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
elseif (empty($u_name)){
echo "Name is empty.";
}
else{
require_once('db-connect.php');
$statement = $mysqli->prepare("INSERT INTO users_data (date, start_time, end_time, user_name, user_email, user_message) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssss', $u_date, $u_starttime, $u_endtime, $u_name, $u_email, $u_text);
if($statement->execute()){
print "Hello, " . $u_name . "!, request is complete!";
}else{
print $mysqli->error;
}
}
}
?>
You can add the 'required' attribute to <input> elements, which get validated on form submission. E.g. <input type="date" name="date" required/> eliminating the necessity to write code for error output.
EDIT: here you can see how the warning is shown
Also, the validation
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
is not required, since the user's choices already force starttime < endtime.
Cheers
Here is an example for setting date validation next to your date input fields.
in process.php:
` $errordate="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
if (empty($u_date)){
$errordate= 'Date is empty!';
}}
and in your index.php:
<input type="date" name="date"/> * <?php echo "<p style='color:red;'>".$errordate . "</p>"; ?>

Why we getting an error as Undefined index and we are losing our data?

we have taken the data and put it into database using php and also done with searching data , the only problem we are facing here is when we hit update button after searching data , we are getting Notice as
Notice: Undefined index: FromD in C:\xampp\htdocs\bkc\update-search.php on line 130
Notice: Undefined index: ToD in C:\xampp\htdocs\bkc\update-search.php on line 131
Notice: Undefined index: Contact in C:\xampp\htdocs\bkc\update-search.php on line 132
Notice: Undefined index: Child in C:\xampp\htdocs\bkc\update-search.php on line 136
and we are losing our FromD , ToD , Contact , Child data from database and getting message "Updation Failed" after hitting update button
NOTE:
FromD, ToD, Contact are text and Child is number/integer
Other is info. is updating Successfully with message "Data Updated"
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search and Update</title>
<style>
.align{
align:center;
}
.grad1 {
height: 600px;
background-color: red;
background-image: linear-gradient(315deg,#F6BB45, #18AA99);
border-radius:20px;
color:white;
}
.container{
margin: 10px 50px 50px 50px;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container grad1 text-center">
<h1>Update Reservation Details</h1>
<form action="" method="POST">
<div class="form-group ">
<label for="exampleInputEmail1"><h5>Email address</h5></label>
<input type="email" class="form-control " name="email" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email to Search">
</div>
<!--
<div class="form-group">
<label for="exampleInputPassword1"><h5>Password</h5></label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
-->
<button type="submit" class="btn btn-warning" name="search" value="Search Data"><h5>Search</h5></button>
</form>
<?php
$conn = mysqli_connect("localhost","root","");
$db = mysqli_select_db($conn,"booking");
if(isset($_POST['search']))
{
$email = $_POST['email'];
$query = "SELECT * FROM bookingt where email='$email' ";
$query_run = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($query_run))
{
?>
<form action="" method="POST">
<div class="form-group">
<br>
<h4>Your Details:</h4>
<p><b>Email:</b>
<input type ="hidden" name="Email" value="<?php echo $row['Email'] ?>"/>
<b>Name:</b>
<input type ="text" name="Name" value="<?php echo $row['Name'] ?>"/></p>
<p><b>Source:</b>
<input type ="text" name="Source" value="<?php echo $row['Source'] ?>"/>
<b>Destination:</b>
<input type ="text" name="Destn" value="<?php echo $row['Destn'] ?>"/></t>
<b>From:</b>
<input type ="text" name="From-D" value="<?php echo $row['FromD'] ?>"/>
<b>To:</b>
<input type ="text" name="To-D" value="<?php echo $row['ToD'] ?>"/></p>
<p><b>Contact:</b>
<input type ="text" name="contact" value="<?php echo $row['Contact'] ?>"/>
<b>Bus:</b>
<input type ="text" name="Bus" value="<?php echo $row['Bus'] ?>"/>
<b>Class:</b>
<input type ="text" name="Class" value="<?php echo $row['Class'] ?>"/></p>
<p><b>No. of adults:</b>
<input type ="number" name="Adult" value="<?php echo $row['Adult'] ?>"/>
<b>No. of childs:</b>
<input type ="number" name="child" value="<?php echo $row['Child'] ?>"/>
<b>No. of Uchilds:</b>
<input type ="number" name="Uchild" value="<?php echo $row['Uchild'] ?>"/></p>
</div>
<button type="submit" class="btn btn-danger" name="update" value="Update Data"><h5>Update</h5></button>
</form>
<?php
}
}
$conn->close();
?>
</div>
</body>
</html>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try{
$conn = mysqli_connect("localhost","root","");
$db = mysqli_select_db($conn,"booking");
} catch(Exception $ex) {
echo "Error";
}
function getPosts()
{
$posts = array();
$posts [0] = $_POST['Name'];
$posts [1] = $_POST['Source'];
$posts [2] = $_POST['Destn'];
$posts [3] = $_POST['FromD'];
$posts [4] = $_POST['ToD'];
$posts [5] = $_POST['Contact'];
$posts [6] = $_POST['Bus'];
$posts [7] = $_POST['Class'];
$posts [8] = $_POST['Adult'];
$posts [9] = $_POST['Child'];
$posts [10] = $_POST['Uchild'];
$posts [11] = $_POST['Email'];
return $posts;
}
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `bookingt` SET `Source`='$data[1]',`Destn`='$data[2]',`Bus`='$data[6]',`Class`='$data[7]',`Adult`='$data[8]',`Child`='$data[9]',`Uchild`='$data[10]',`FromD`='$data[3]',`ToD`='$data[4]',`Name`='$data[0]',`Contact`='$data[5]' WHERE `Email`='$data[11]' ";
try{
$update_Result = mysqli_query($conn, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($conn) > 0)
{
echo "Data Updated !!!";
}
else
{
echo " Updation Failed";
}
}
} catch(Exception $ex){
echo "Error Update ".$ex->getMessage();
}
}
$conn->close();
?>
The field names in form and PHP code need to be identical. These names are also case sensitive. Correct the PHP code so that you are using the names as in html form. For example change ToD to To-D, Child to child etc
Check the "FromD", "ToD", "Contact" and "Child" names are available in the form which you're submitting.
I think you're missed or misspelled the name attribute for that 4 fields in the form...
Are you using a form or doing an ajax call?

Edit functionality not works Php MySql

This is the code for edit.php where when I click edit this page opens and edits that specific line.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body><?php // if there are any errors, display them
if ($error != ''){echo '
<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label><br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" /><br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b><br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" /><br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" /><br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" /><br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" /><br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" /><br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" /><br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back();return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php } // connect to the database
include('connect.php');// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])){// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])){// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$telephone_number = mysql_real_escape_string(htmlspecialchars($_POST['telephone_number']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$job_title = mysql_real_escape_string(htmlspecialchars($_POST['job_title']));
$workplace = mysql_real_escape_string(htmlspecialchars($_POST['workplace']));
$country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$nationality = mysql_real_escape_string(htmlspecialchars($_POST['nationality']));// check that firstname/lastname fields are both filled in
if ($name == ''){// generate error message
$error = 'ERROR: Please fill in all required fields!';//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else{// save the data to the database
$link->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");// once saved, redirect back to the view page
header("Location: view.php");
}
}
else{// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else{ // if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){// query db
$id = $_GET['id'];
$result = $link->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);// check that the 'id' matches up with a row in the databse
if($row){// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];// show form //renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else{// if no match, display result
echo "No results!";
}
}
else{// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
It gives first warning that mysql is deprecated so I used below syntax but still it gives error:
mysqli_real_escape_string(htmlspecialchars($link,$_POST['name']));
Second major error its giving is that it takes me to this error message and makes all form fields empty. The line its showing always is:
ERROR: Please fill in all required fields!
Please Guide!
$servername = "localhost:3306";
$username = "root";
$password = "<Password here>";
$dbname = "TUTORIALS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tutorials_inf(name)VALUES ('".$_POST["name"]."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
I Solved My-Self...
Code Below...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<!--HTML form -->
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label>
<br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" />
<br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b>
<br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" />
<br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" />
<br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" />
<br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" />
<br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" />
<br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" />
<br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php
}
// connect to the database
$mysqli = new mysqli("sql213.byethost7.com", "b7_21234466", "mazhar2012", "b7_21234466_conference");
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = $mysqli->real_escape_string($_POST['name']);
//$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
//$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$telephone_number = $mysqli->real_escape_string($_POST['telephone_number']);
$email = $mysqli->real_escape_string($_POST['email']);
$job_title = $mysqli->real_escape_string($_POST['job_title']);
$workplace = $mysqli->real_escape_string($_POST['workplace']);
$country = $mysqli->real_escape_string($_POST['country']);
$nationality = $mysqli->real_escape_string($_POST['nationality']);
// check that firstname/lastname fields are both filled in
if ($name == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else
{
// save the data to the database
$mysqli->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = $mysqli->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];
// show form
//renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
$link->query($conn,"UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");

HTML form input for MySQL

I have a MySQL table named as letter and wish to insert records through the HTML data input form. Code as follows:
<head>
<meta charset="utf-8">
<link href="css/jquery-ui-1.10.1.css" rel="stylesheet">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui-1.10.1.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker(({ dateFormat: "yy-mm-dd" }));
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add Letter</title>
<style type="text/css" media="screen">
#import "style_contactform.css";
</style>
</head>
<?php
$querymethod = "select r_method_code, r_method from r_method order by r_method";
$resultmethod = mysql_query($querymethod) or die ( mysql_error());
$querybranch = "select bcode, branch from branch order by branch";
$resultbranch = mysql_query($querybranch) or die ( mysql_error());
$querytype = "select tcode, type from type order by type";
$resulttype = mysql_query($querytype) or die ( mysql_error());
?>
<?php
if (isset($_POST["submit"]))
{
$rno =$_POST["rno"];
$lno =$_POST["lno"];
$dol = mysql_real_escape_string($_POST["doi"]);
$hdg =$_POST["hdg"];
$from =$_POST["from"];
$address =$_POST["address"];
$method =$_POST["method"];
$type =$_POST["type"];
$branch =$_POST["branch"];
if ((empty($hdg))){
echo '<script language="javascript">';
echo 'alert("All fields must be required")';
echo '</script>';
}
else
{
$query ="INSERT INTO letter (reference_no, letter_no, date_stamp, heading, from_1, address, r_method_code, tcode, bcode) VALUES ('$rno', '$lno', '$dst', '$hdg', '$from', '$address', '$method', '$type', '$branch')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
echo '<script language="javascript">';
echo 'alert("Added Successfully")';
echo '</script>';
}
}
?>
<html>
<form id="contactform">
<div class="formcolumn">
<label for="rno">Reference No:</label>
<input type="text" name="rno" />
<label for="lno">Letter No:</label>
<input type="text" name="lno" />
<label for="dst">Date of the Letter:</label>
<input type="text" name="dst" id="datepicker" />
<label for="hdg">Heading:</label>
<textarea name="hdg"></textarea>
</div>
<div class="formcolumn">
<label for="from">From 1:</label>
<input type="text" id="from" />
<label for="address">Address:</label>
<textarea id="address"></textarea>
<label for="method">Received Method:</label>
<select name="method" span class="al">
<?php
do {
?>
<option value="<?php echo $rowmethod['r_method_code']?>"><?php echo $rowmethod['r_method']?></option>
<?php
} while ($rowmethod = mysql_fetch_assoc($resultmethod));
?>
</select>
<label for="type">Type:</label>
<select name="type" span class="al">
<?php
do {
?>
<option value="<?php echo $rowtype['tcode']?>"><?php echo $rowtype['type']?></option>
<?php
} while ($rowtype = mysql_fetch_assoc($resulttype));
?>
</select>
<label for="branch">Branch:</label>
<select name="branch" span class="al">
<?php
do {
?>
<option value="<?php echo $rowbranch['bcode']?>"><?php echo $rowbranch['branch']?></option>
<?php
} while ($rowbranch = mysql_fetch_assoc($resultbranch));
?>
</select>
</div>
<div class="buttons">
<input class="button" type="submit" value="Submit!" />
</div>
</form>
</html>
But I was unable to add records through this form to the relevant table. I can not understand what I am going wrong. Can any one help me?... Pls...
Form's Attribute method's default value is get
You should specify it like this
<form id="contactform" method="post">
Now you can use $_POST to get data!

PHP code looks fine but not updating

I am currently creating a cms, all is fine apart from the add.php page.
My code for this page is this:
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$image = $_POST['Image URL'];
$link = $_POST['Link'];
$price = $_POST['Price'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
$query->execute(array(
':title' => $title,
':content' => $content,
':image' => $image,
':link' => $link,
':price' => $price
));
$query->execute();
}if($result){
echo("<br>Input data is successful");
} else{
echo("<br>Input data failed");
}
}
?>
<html>
<head>
<title>testing</title>
<link rel="stylesheet" href="../style.css" />
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form name = "myform" action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input type="text" name="Image URL" placeholder="Image URL" /><br /><br />
<input type="text" name="Link" placeholder="Link" /><br /><br />
<input type="text" name="Price" placeholder="Price" /><br /><br />
<input type="submit" name="submit" value="Add Article" />
</form>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
error_reporting(E_ALL);
?>
My problem is. My code is not showing any errors in my error log and people tellme that it is fine. But it is not adding to the database. is there a way that I can break down each bit of code and find out what is going on?
or is there a way to display what the error may be? my error reporting is turned on with E_ALL | E_STRICT and still nothing.
please help
thank you.
You need to change your PDO query from
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
to be something like this
$query = $pdo->prepare('INSERT INTO `apps`(`app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:title,:content,:img,:link,:price)');
You should review how PDO::prepare method work with placeholders. Besides, if your app_id is an auto increment field. You need not include it in your insert query.
I'm not sure how this could work as the placeholders aren't using the correct notation and aren't named correctly.
Your query should look like:
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:app_id, :app_title, :app_content, :app_img, :app_link, :app_price)');
$query->execute(array(
':app_id' => ???,
':app_title' => $title,
':app_content' => $content,
':app_img' => $image,
':app_link' => $link,
':app_price' => $price
));
Also you appear to be missing the :app_id parameter.

Categories