I am trying to send info I enter into an HTML form, into a MySQL database table. The function works, BUT...It enters BLANK data into the Mysql Database
I dont know what else to try. I am really new to this
THIS IS MY HTML FORM:
<form action="" method="post">
<div class="form-group">
<label for="date">Date</label>
<input type="date" class="form-control" id="date" aria-describedby="emailHelp" placeholder="Date">
<small id="emailHelp" class="form-text text-muted">The date the team went to the job site</small>
</div>
<div class="form-group">
<label for="job_number">Job Number</label>
<input type="text" class="form-control" id="job_number" placeholder="JC2020">
</div>
<div class="form-group">
<label for="job_name">Job Name</label>
<input type="text" class="form-control" id="job_name" placeholder="AVI Tender">
</div>
<div class="form-group">
<label for="team_name">Team Name</label>
<input type="text" class="form-control" id="team_name" placeholder="Shane">
</div>
<div class="form-group">
<label for="pastel_code">Pastel Code</label>
<input type="text" class="form-control" id="pastel_code" placeholder="012">
</div>
<div class="form-group">
<label for="vrn">Vehicle Registration</label>
<input type="text" class="form-control" id="vrn" placeholder="ND 123-456">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
THIS IS MY PHP file that processes the data:
<?php
require_once('config.php');
$date= $_POST['date'];
$job_number= $_POST['job_number'];
$team_name= $_POST['team_name'];
$pastel_code= $_POST['pastel_code'];
$vrn= $_POST['vrn'];
$job_name= $_POST['job_name'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO job_records (date, job_number, team_name, pastel_code, vrn, job_name)
VALUES ('$date', '$job_number', '$team_name', '$pastel_code', '$vrn', '$job_name')";
$conn->exec($sql);
echo "<script>alert('Data successfully added!'); window.location='dataentry.php'</script>";
?>
After submitting the form, a message displays saying the data was added, then redirects to the "master data" page with ALL the entries i have entered over time. But all entries i process come out BLANK. What am i doing wrong?
As I mentioned each form element requires a name attribute in order that it will appear in the POST array when the form is submitted. An ID attribute is mainly of use when interacting with the DOM using Javascript so really are not required below / above.
<form action='' method='post'>
<div class='form-group'>
<label for='date'>Date</label>
<input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
<small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
</div>
<div class='form-group'>
<label for='job_number'>Job Number</label>
<input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
</div>
<div class='form-group'>
<label for='job_name'>Job Name</label>
<input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
</div>
<div class='form-group'>
<label for='team_name'>Team Name</label>
<input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
</div>
<div class='form-group'>
<label for='pastel_code'>Pastel Code</label>
<input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
</div>
<div class='form-group'>
<label for='vrn'>Vehicle Registration</label>
<input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
</div>
<button type='submit' class='btn btn-primary'>Submit</button>
</form>
That said the main issue, which has been addressed in comments, is that of SQL injection vulnerabilities - one of the benefits of both PDO and mySQLi are prepared statements. As you are using PDO perhaps this might be of use:
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
require_once('config.php');
$args=array(
'date' => FILTER_SANITIZE_STRING,
'job_number' => FILTER_SANITIZE_STRING,
'team_name' => FILTER_SANITIZE_STRING,
'pastel_code' => FILTER_SANITIZE_STRING,
'vrn' => FILTER_SANITIZE_STRING,
'job_name' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
$params=array();
$sql='insert into `job_records` ( `date`, `job_number`, `team_name`, `pastel_code`, `vrn`, `job_name` ) values ( :date, :job_number, :team_name, :pastel_code, :vrn, :job_name )';
foreach( array_keys( $args ) as $key ){
$params[ ':'.$key ] = ${$key};
}
$stmt=$conn->prepare( $sql );
$res = $stmt->execute( $params );
exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) );
}
?>
demo - tested and appears to function OK
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
/* PDO connection */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$options=array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', ##sql_mode = STRICT_ALL_TABLES, ##foreign_key_checks = 1'
);
$dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
$db = $conn = new PDO( $dsn, $dbuser, $dbpwd, $options );
/* disabled as not relevant in demo */
#require_once('config.php');
$args=array(
'date' => FILTER_SANITIZE_STRING,
'job_number' => FILTER_SANITIZE_STRING,
'team_name' => FILTER_SANITIZE_STRING,
'pastel_code' => FILTER_SANITIZE_STRING,
'vrn' => FILTER_SANITIZE_STRING,
'job_name' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$errors=array();
$params=array();
$keys=array_keys( $args );
/* dynamically build sql query from $args array */
$sql=sprintf('insert into `job_records`
( `%s` )
values
( :%s ) ',
implode( '`,`', $keys ),
implode( ', :', $keys )
);
/* check that each variable is set else throw exception and continue */
foreach( array_keys( $args ) as $key ){
try{
/* test variable variable against those generated by `extract` above */
if( empty( ${$key} ) ) throw new Exception( sprintf( 'empty field: %s', $key ) );
/* add the parameter to the args to be executed */
$params[ ':'.$key ] = ${$key};
}catch( Exception $e ){
$errors[]=$e->getMessage();
continue;
}
}
/* If all went well execute the query & redirect user */
if( !empty( $params ) && empty( $errors ) && !empty( $conn ) ){
$stmt=$conn->prepare( $sql );
if( !$stmt ) throw new PDOException('Failed to prepare SQL Query');
$res = $stmt->execute( $params );
exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) );
}
if( !empty( $errors ) ) printf( '<pre>%s</pre>', print_r($errors,true) );
}catch( PDOException $e ){
exit( $e->getMessage() );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>PDO form test</title>
</head>
<body>
<form action='' method='post'>
<div class='form-group'>
<label for='date'>Date</label>
<input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
<small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
</div>
<div class='form-group'>
<label for='job_number'>Job Number</label>
<input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
</div>
<div class='form-group'>
<label for='job_name'>Job Name</label>
<input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
</div>
<div class='form-group'>
<label for='team_name'>Team Name</label>
<input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
</div>
<div class='form-group'>
<label for='pastel_code'>Pastel Code</label>
<input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
</div>
<div class='form-group'>
<label for='vrn'>Vehicle Registration</label>
<input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
</div>
<button type='submit' class='btn btn-primary'>Submit</button>
</form>
</body>
</html>
Your code is correct but the error create on your input field
In simple and short use name(Attribute) on the input field and pass that name to save the data.
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
Retrive form value and insert in to database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Conclusion for your code error
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO job_records ('database column name with comma seperated')
VALUES ('Input variable value seperated by comma')";
Related
i am very new at all of this... Here is my code (which i originally got from here)
<?php
/**
* Use an HTML form to create a new entry in the
* users table.
*
*/
if (isset($_POST['submit'])) {
require "../config.php";
require "../common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_user = array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"email" => $_POST['email'],
"age" => $_POST['age'],
"location" => $_POST['location']
);
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"users",
implode(", ", array_keys($new_user)),
":" . implode(", :", array_keys($new_user))
);
$statement = $connection->prepare($sql);
$statement->execute($new_user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) { ?>
<blockquote><?php echo $_POST['firstname']; ?> successfully added.</blockquote>
<?php } ?>
<h2>Add a user</h2>
<form method="post">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname">
<label for="email">Email Address</label>
<input type="text" name="email" id="email">
<label for="age">Age</label>
<input type="text" name="age" id="age">
<label for="location">Location</label>
<input type="text" name="location" id="location">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
This code worked just fine without fk columns. But in PHPAdmin I now made "location" a foreign column. The parent table looks like this:
Location
location INT (PK)
location name VARCHAR
I added a few locations to the parent table but still when i execute the code above, this error appears:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'location' cannot be null
How do I define the foreign key? Do I need a SELECT statement? I tried several things but I just cannot make it work. I'm about to give up so I'm posting on here.
Thank you very much for any answer!
PS: Maybe anybody can recommend any reading/books on this specific topic of PHP/PDO/SQL?
I have an application where a user can send request edit to the admin, now the problem is how to store the id of the requested asset from user_asset table to the request table so I can display it to the admin's page with full details of the asset
when the user clicks on the request edit he gets a form with editable fields filled with current information but how can I store this asset's id so I can fetch it to the admin's table with information from both tables (user_assets, requests)
I have user_asset table
asset_id
asset_category
code
title
userid
and requests table
id
reason
assetid
user_id
this is what I have done so far
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
?>
and this is my form
<form method="post" action="req_ade.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
these are the errors I'm getting
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Incorrect integer value: '' for column 'assetid' at row 1' in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
( ! ) mysqli_sql_exception: Incorrect integer value: '' for column 'assetid' at row 1 in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
There is no "id" in your $_GET array. So your $asset_id variable will be empty and a empty string is not a valid int number. You should add (int) in your query:
mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". (int)$asset_id ."','" .$_SESSION['user_id'] . "')")
Or better check the the $_GET array before you use it. Like this:
If(isset($_GET['id']))
{
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
}
else
{
...
}
Thank you for all your suggestions.
After trying a lot of suggestions and manipulating with the code I have found a solution for it.
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_POST['asset_id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests1`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
and this is the form I have posted the asset_id in a hidden type
<form method="post" action="req_ade1.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="hidden" value="<?php echo $project['asset_id'];?>" name="asset_id" />
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
sign_up page
<html>
<head>
<meta name="keywords" content="example, Javascript Form Validation, Sample registration form" />
</head>
<body>
<form name="registration" method="post" action= '<?php $_SERVER["PHP_SELF"] ?>'>
<label for="user">USERNAME</label>
<input name="user" type="text" id="username" placeholder="should not contain spaces" required><br><br>
<label for="email">EMAIL</label>
<input name="email" type="email" id="email" placeholder="eg: abc#xyz.com" required><br><br>
<label for="pass">PASSWORD</label>
<input name="pass" type="password" id="password" placeholder="atleat 8 characters" required><br><br>
<label for="conf_pass">CONFIRM PASSWORD</label>
<input name="conf_pass" type="password" id="conf_pass" placeholder="atleat 8 characters" required><br><br>
<label for="mobile">MOBILE NO</label>
<input name="mobile" type="number" id="mobile" placeholder="should contain 10 digits" required><br><br>
<label for="dob">DATE OF BIRTH</label>
<input name="dob" type="date" id="dob" required><br><br>
<input type="submit" name="signup" id="submit" value="Submit">
</form>
</body>
</html>
===============================================================================
<?php
$conn=new mysqli("localhost","khushank","sethi","emp");
if(!$conn){
echo "unable to connect".$conn->connect_error();
}
if($_SERVER['REQUEST_METHOD']=='POST') {
if(isset($_POST['signup'])){
$user=$_POST['user'];
$email=$_POST['email'];
$psw=$_POST['pass'];
$conf_psw=$_POST['conf_pass'];
$mob=(int)$_POST['mobile'];
$dob=$_POST['dob'];
if($psw!=$conf_psw){
echo"<script type='text/javascript'>".'alert(confirm password and password should be same");
</script>';
}
else{
$sel="SELECT userid FROM details WHERE userid='$user'";
$sql="INSERT INTO details(userid,email,pass,mobile,date_of_birth) VALUES(?,?,?,?,?)";
$res=$conn->query($sel);
if($res->num_rows!=0){
echo"<script type='text/javascript'>".'alert("username already exists");
</script>';
}
else{
$stmt=$conn->prepare($sql);
$stmt->bind_param('sssis', $user, $email, $pass, $mob, $dob);
if($stmt->execute()){
header('location:login.php');
}
$stmt->close();
}
}
}
}
$conn->close();
?>
Change
action= '<?php $_SERVER["PHP_SELF"] ?>
to
action= '<?php echo $_SERVER["PHP_SELF"] ?>
and move the php loops and db connection at top of the form
If the above is the actual code of your page then there are problems. To use header you need to do so before sending any HTML content to the browser ( though you can use output buffering to mitigate this requirement but not best practise ) - so it is likely that you are getting errors logged but clearly not displayed otherwise you would have mentioned them in the question?
Also, lines like below will cause errors.
echo"<script type='text/javascript'>".'alert(confirm password and password should be same");
</script>';
A few minor alterations - placing the php code before the HTML should help when it comes to errors relating to the use of header, simplifying the javascript variables and subsequent display. Remove PHP_SELF as the form action - it is vulnerable to abuse and, as you post to the same page, is not required at all.
<?php
try{
$message=false;
if( $_SERVER['REQUEST_METHOD']=='POST' ) {
$conn=new mysqli( "localhost", "khushank", "sethi", "emp" );
if( !$conn ) throw new Exception( sprintf( "Unable to connect: %s", $conn->connect_error() ), 1 );
/*
ensure that other required fields are in the submitted data
*/
if( isset(
$_POST['signup'],
$_POST['user'],
$_POST['email'],
$_POST['pass'],
$_POST['conf_pass'],
$_POST['mobile'],
$_POST['dob']
)){
$user=$_POST['user'];
$email=$_POST['email'];
$psw=$_POST['pass'];
$conf_psw=$_POST['conf_pass'];
$mob=(int)$_POST['mobile'];
$dob=$_POST['dob'];
/* passwords do not match - abort processing here */
if( $psw !== $conf_psw ){
$message='confirm password and password should be same';
} else{
/* try to locate user in db */
$sql="select `userid` from `details` where `userid`=?";
$stmt=$conn->prepare( $sql );
if( !$stmt ) throw new Exception( 'Failed to prepare sql query', 3 );
$stmt->bind_param('s', $user );
$res=$stmt->execute();
if( $stmt->num_rows == 0 ){
/* user does not already exist */
$sql="insert into `details` ( `userid`, `email`, `pass`, `mobile`, `date_of_birth` ) values( ?,?,?,?,? )";
/* clean up from previous query */
$stmt->free_result();
$stmt->close();
/* prepare new query */
$stmt=$conn->prepare( $sql );
if( !$stmt ) throw new Exception( 'Failed to prepare sql query', 4 );
/* bind and execute */
$stmt->bind_param( 'sssis', $user, $email, $pass, $mob, $dob );
$result = $stmt->execute();
/* this should be exactly 1 */
$count = $conn->affected_rows;
$stmt->close();
$conn->close();
if( $count===1 )header( 'Location: login.php' );
} else {
$message='username already exists';
}
}
$conn->close();
} else {
throw new Exception( 'Missing or empty values in POST data', 2 );
}
}
}catch( Exception $e ){
exit( sprintf( 'Exception: %s, Code: %d', $e->getMessage(), $e->getCode() ) );
}
?>
<html>
<head>
<meta name='keywords' content='example, Javascript Form Validation, Sample registration form' />
<title>User registration</title>
</head>
<body>
<form name='registration' method='post'>
<label for='user'>USERNAME</label>
<input name='user' type='text' id='username' placeholder='should not contain spaces' required>
<br><br>
<label for='email'>EMAIL</label>
<input name='email' type='email' id='email' placeholder='eg: abc#xyz.com' required>
<br><br>
<label for='pass'>PASSWORD</label>
<input name='pass' type='password' id='password' placeholder='atleat 8 characters' required>
<br><br>
<label for='conf_pass'>CONFIRM PASSWORD</label>
<input name='conf_pass' type='password' id='conf_pass' placeholder='atleat 8 characters' required>
<br><br>
<label for='mobile'>MOBILE NO</label>
<input name='mobile' type='number' id='mobile' placeholder='should contain 10 digits' required>
<br><br>
<label for='dob'>DATE OF BIRTH</label>
<input name='dob' type='date' id='dob' required>
<br><br>
<input type='submit' name='signup' id='submit' value='Submit'>
</form>
<?php
/* If there was an error, use a javascript alert to inform user */
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $message ) ){
printf( '<script>alert("%s");</script>', $message );
}
?>
</body>
</html>
Hope it helps...
Iam trying to update my form fields with a simple update statement. However when I execute the statement it wont update.
Iam using PDO::FECTH_CLASS to store my values into my object, and thats how I check if the id is equal to the id I want to update.
This is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try{
$firstname = $_POST['firstname'];
$paragraph = $_POST['paragraph'];
$company = $_POST['companyName'];
$q = 'UPDATE `testimonials` SET paragraph`= :paragraph,
`name`= :name,
`company`=:company,
`dateAdded`= NOW()
WHERE `id` =:id';
$stmt = $pdo->prepare($q);
$stmt->execute(array( ':id' => $testimonials->getId(), ':paragraph' => $paragraph, ':name' => $firstname, ':company' => $company));
}catch( PDOException $Exception ) {
throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}
}
?>
<section>
<form action="" method="POST">
<label for=""></label>
<input type="text" name="firstname" value="<?php echo $testimonials->getName();?>">
<input type="text" name="companyName" value="<?php echo $testimonials->getCompany(); ?>">
<textarea name="paragraph"><?php echo $testimonials->getParagraph(); ?></textarea>
<input type="submit" name="submit">
</form>
</section>
Hi so I have a form with 10 fields and I am trying to insert them on an SQL databse through posting them on a PHP page. Connection starts fine, but it returns the error below:
Error: INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES (, , , , , , , , , )
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , , , , , , )' at line 1
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$teacher = $_POST['teacher'];
$description = $_POST['description'];
$class = $_POST['class'];
$dayone = $_POST['dayone'];
$daytwo = $_POST['daytwo'];
$daythree = $_POST['daythree'];
$std1 = $_POST['std1'];
$std2 = $_POST['std2'];
$std3 = $_POST['std3'];
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ($name, $teacher, $description, $class, $dayone, $daytwo, $daythree, $std1, $std2, $std3)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
I should also mention that the database table has one more field called ID type int(11) which is AUTO_INCREMENT and I expect it to be automatically filled everytime a new row is inserted. Am I wrong?
EDIT: Added HTML code since it has been asked
<form name="registration_form" method="post" class="clearfix" action="create.php">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" id="name" placeholder="Course Name">
</div>
<div class="form-group">
<label for="teacher">Teacher</label>
<input type="text" class="form-control" id="teacher" placeholder="Teacher's Name">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" placeholder="Description"></textarea>
</div>
<div class="form-group">
<label for="class">Class</label>
<input type="text" class="form-control" id="class" placeholder="Class Name">
</div>
<div class="form-group">
<label for="dayone">Day one</label>
<input type="text" class="form-control" id="dayone" placeholder="Day One">
</div>
<div class="form-group">
<label for="daytwo">Day two</label>
<input type="text" class="form-control" id="daytwo" placeholder="Day Two">
</div>
<div class="form-group">
<label for="daythree">Day three</label>
<input type="text" class="form-control" id="daythree" placeholder="Day Three">
</div>
<div class="form-group">
<label for="std1">std1</label>
<input type="text" class="form-control" id="std1" placeholder="std1">
</div>
<div class="form-group">
<label for="std2">std2</label>
<input type="text" class="form-control" id="std2" placeholder="std2">
</div>
<div class="form-group">
<label for="std1">std3</label>
<input type="text" class="form-control" id="std3" placeholder="std3">
</div>
<div class="checkbox">
<label>
<input type="checkbox">I Understand Terms & Conditions
</label>
</div>
<button type="submit" class="btn pull-right">Create Course</button>
</form>
This should help you identify if the issue is POST variables not being received.
Also a little bit more security.
// create an array of all possible input values
$input_array = array('name', 'teacher', 'description', 'class', 'dayone', 'daytwo', 'daythree', 'std1', 'std2', 'std3');
// create an input array to put any received data into for input to the database
$input_array = array();
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// loop through the possible input values to check that a post variable has been received for each.. if received escape the data ready for input to the database
foreach($input_array as $key => $value)
{
if(!isset($_POST[$value])) {
die("no {$value} post variables received");
}
$input_array[$value] = mysqli_real_escape_string($conn, $_POST[$value]);
}
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('{$input_array['name']}', '{$input_array['teacher']}', '{$input_array['description']}', '{$input_array['class']}', '{$input_array['dayone']}', '{$input_array['daytwo']}', '{$input_array['daythree']}', '{$input_array['std1']}', '{$input_array['std2']}', '{$input_array['std3']}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Try:
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('".$name."', '".$teacher."', '".$description."', '".$class."', '".$dayone."', '".$daytwo."', '".$daythree."', '".$std1."', '".$std2."', '".$std3."')";
Also, use:
$name = $conn->real_escape_string($_POST['name']);
//etc
Also add name to your form fields:
<input name="class" type="text" class="form-control" id="class" placeholder="Class Name">