INSERT INTO `test`.`lecturer` (`lecturerID`, `course_ID`, `lecturerFirstName`, `lecturerLastName`, `lectureremail`, `lecturerpassword`) VALUES (NULL, NULL, 'test', 'test', 'a#gmail.com', '123456');
Provided was the test code I keyed in into my phpmyadmin, lecturerID was the primary key and also had auto increment on, by my understanding i wasnt suppose to key in anything there and the sql server will input the next number for me, however I keep getting #1062 - Duplicate entry '0' for key 'PRIMARY'. Anyone maybe can give me some insight why am i facing this? Thanks.
Full Code:
<?php include_once "/_core/core.php"; ?>
<?php
if(isset($_POST['id']))
{
$delid = mysql_real_escape_string($_POST['id']);
$sql="DELETE FROM lecturer WHERE lecturerID='$delid'";
mysql_query($sql);
}
if(isset($_POST['fname']) and ($_POST['lname']) and ($_POST['email']) and ($_POST['password']))
{
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
echo $fname, $lname, $email, $password;
$sql = 'INSERT INTO lecturer (lecturerID, course_ID, lecturerFirstName, lecturer_LastName, lectureremail, lecturerpassword) VALUES (NULL,"0","'.$fname.'","'.$lname.'","'.$email.'","'.$password.'")';
mysql_query($sql);
}
?>
<?php
if(!empty($_SESSION['Admin']) && !empty($_SESSION['Username']))
{
?>
<?php include "_core/menubar.php"; ?>
<br><br><br>
<form class="form-horizontal" action="add_lecturer.php" method="POST">
<fieldset>
<!-- Form Name -->
<legend>Add lecturer</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="fname">First Name</label>
<div class="col-md-4">
<input id="fname" name="fname" type="text" placeholder="First Name" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="lname">Last Name</label>
<div class="col-md-4">
<input id="lname" name="lname" type="text" placeholder="Last Name" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-5">
<input id="email" name="email" type="text" placeholder="test#apu.edu.my" class="form-control input-md" required="">
</div>
</div>
<!-- Password-->
<div class="form-group">
<label class="col-md-4 control-label" for="password">Password</label>
<div class="col-md-4">
<input id="password" name="password" type="password" placeholder="*****" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
<?php
$query = ('SELECT * FROM lecturer');
$q = mysql_query($query);
if(mysql_num_rows($q) > 0)
{
?>
Lecturer List
<table class="table table-striped table-hover">
<form action="add_lecturer.php" method="post">
<?php
while($row = mysql_fetch_array($q)) {
echo "<tr>";
echo "<td>" . $row['lecturerID'] . "</td>";
echo "<td>" . $row['lecturerFirstName'] . "</td>";
echo "<td>" . $row['lecturerLastName'] . "</td>";
echo "<td>" . $row['lectureremail'] . "</td>";
echo '<td><input type="submit" name="deleteItem" value="Delete" /></td>';
echo '<td><input type="hidden" id="id" name="id" value="'.$row['lecturerID'].'" /></td>';
echo "</tr>";
}
?>
</table>
</form>
<?php
}
else
{
echo "You have no lecturers added!";
}
?>
<?php
}
else
{
echo "<meta http-equiv='refresh' content='2;index.php' />";
?>
<?php include "../_class/login.php"; ?>
<?php
}
?>
</div>
<?php include "../_class/footer.php"; ?>
You have to pass NULL for auto increment column not Blank value like this
INSERT INTO `test`.`lecturer`
(`lecturerID`, `course_ID`, `lecturerFirstName`, `lecturerLastName`, `lectureremail`, `lecturerpassword`)
VALUES (NULL, NULL, 'test', 'test', 'a#gmail.com', '123456');
You should assign NULL value to that auto increment column:
INSERT INTO `test`.`lecturer`
(`lecturerID`, `course_ID`, `lecturerFirstName`, `lecturerLastName`, `lectureremail`, `lecturerpassword`)
VALUES
(NULL, NULL, 'test', 'test', 'a#gmail.com', '123456');
Or you can try insert without specifying that column in your query as follows:
INSERT INTO `test`.`lecturer`
(`course_ID`, `lecturerFirstName`, `lecturerLastName`, `lectureremail`, `lecturerpassword`)
VALUES
(NULL, 'test', 'test', 'a#gmail.com', '123456');
INSERT INTO `test`.`lecturer` (`lecturerID`, `course_ID`, `lecturerFirstName`, `lecturerLastName`, `lectureremail`, `lecturerpassword`)
VALUES ('', '', 'test', 'test', 'a#gmail.com', '123456');
you must have your assign key auto increment in sql database
Related
I have a form in a plugin I am creatingin wordpress. The form is a simple test form and it has a hidden field and two text fields. If I enter a number into the text fields, it doesn't process it when I hit submit, it takes to me a page that says
It looks like nothing was found at this location. Maybe try a search?
here is the entire plugin showing the form and the action that processes the form.
<?php
/*
plugin name: deano plugin
description: deano test database to insert data into books table
author: Dean-O
*/
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once($path.'/wp-load.php');
function deanoinsertdata() {
/**
* Dean-O database insert book function
*/
global $wpdb;
if(isset($_POST['submitbtn'])){
error_log('I am here');
$data=array(
'wp_id'=>$_POST['wp_id'],
'title'=>$_POST['title'],
'author'=>$_POST['author'],
);
$table_name = 'books';
$foundOne = 1;
error_log('table_name = '.$table_name);
error_log('foundOne = '.$foundOne);
/*$wp_idin = $_POST['wp_id'];
$titlein = $_POST['title'];
$authorin = $_POST['author'];
*/
$wp_idin = $data['wp_id'];
$titlein = $data['title'];
$authorin = $data['author'];
error_log('wp_idin = '.$wp_idin);
error_log('titlein = '.$titlein);
error_log('author = '.$authorin);
/*
see if the record is already in the table
*/
$sql = "select * from books";
print $sql;
$results = $wpdb->get_results($sql);
foreach($results as $result) {
if($result->wp_id==$wp_idin && $result->title==$titlein && $result->author==$authorin)
{
$foundOne = 0;
error_log('foundOne = 0');
}
}
//error_log('logged message');
if($foundOne==1) {
error_log('foundOne = 1 before insert');
$resultinsert = $wpdb->insert($table_name,$data);//, $format=NULL);
error_log('insert executed');
error_log('resultinsert = '.$resultinsert);
//wp_redirect( "http://localhost/tadpolewp/deano-plugin--duplicate-records/" );
//exit();
if($resultinsert==1) {
//header('Location: http://localhost/tadpolewp/deano-plugin-successful/');
error_log( 'successful' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/" );
exit();
http://localhost/tadpolewp/deano-plugin-successful/
//error_log('Book saved 1');
//echo "Book Saved 1";
} else {
//header('Location: http://localhost/tadpolewp/deano-plugin-failed/');
error_log( 'failed to save' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-failed/" );
exit();
//error_log('unable to save');
//echo "Unable to Save";
}
} else {
//error_log('Duplicate record found');
//echo "Duplicate recortd found";
//header('Location: http://localhost/tadpolewp/deano-plugin-duplicate-records/');
error_log( 'duplicate record' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-duplicate-records/" );
exit();
}
}
?>
<form role="form" method="post">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
<?php
}
add_shortcode('deanoputdatain','deanoinsertdata');
?>
The only way I can get the Field 1 or Field 2 to take numbers is to change them to type="number"
Is there a varchar type that I can use?
My database has the field set as a varchar.
Thanks in advance
Dean-O
You should be set action for your form.
For example: 'test.php' or '/'.
It worked well for me. I rewrite your code here:
<form role="form" method="post" action="{your menu slug}">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
I want to send the value of disabled checkbox into the database. I tried to set it to readonly but it is allowing user to check/uncheck the field.
<?php
if(isset($_POST['bookbtn'])){
if(!empty($_POST['checky'])) {
$lang = implode(",",$_POST['checky']);
// Insert and Update record
$checkEntries = mysqli_query($conn,"SELECT * FROM seats");
if($test == $hotel)
$ic = "update seats set seat='$lang' where hotelname='$test' ";
mysqli_query($conn,$ic);
}else{
$del = "insert into seats (hotelname,seat) values ('$test','$lang')";
mysqli_query($conn,$del);
}
}
// code for checkbox
<form method="post">
<div><input type="submit"class="button1" name="bookbtn" value="Book Your table" onclick="bookbtn()"/>
<input type="reset" class="button1"name="resetboxes"value="Reset"></div><br><br><div id="mask2"style="float:left;width:20%;">
<?php $i=1;
while ($i<=$tab)
{?>
<div class="TWO">
<div class="check"style="height:40px;width:120px;">
<div class="seconda">
</div>
<div class="secondb">
<input type ="checkbox"name="checky[]"id="<?php echo "two".$i;?>"class="tabtwo"style="width:30px;height:30px;"
value="<?php echo "two".$i;?>"
<?php if (in_array("two".$i, $expcheck)) {?>
checked="checked"<?php }else {echo "none";}?>disabled>
</div>
<div class="secondc">
</div>
</div>
</div>
<?php
$i++;
}
?>
try this
<input type="checkbox" onclick="this.checked=this.defaultChecked" />
<input type="checkbox" checked onclick="this.checked=this.defaultChecked" />
i have a bootstrap one page with a contact form in the end. I would like on submission to focus on that section and not at the beginning of the page.
So, if the message was send, the users will see the OK message, else they will read the error.
here is my code.
Html
<section id="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 class="heading">Contact</h2>
<div class="row">
<div class="col-md-12">
<?php
$to = 'mail#mail.mm';
$subject = 'Enquiry from the website';
$contact_submitted = 'Your message was submitted and will be responded to as soon as possible. Thank you for contacting us.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<div class="form-group">
<label for="Name :">Your firstname *</label>
<input type="text" name="your_name" placeholder="Enter your firstname" required="required" class="form-control">
</div>
<div class="form-group">
<label for="Email Address :">Your email *</label>
<input type="email" name="your_email" placeholder="Enter your email" required="required" class="form-control">
</div>
<div class="form-group">
<label for="Message :">Your message for us *</label>
<textarea rows="4" name="your_message" placeholder="Enter your message" required="required" class="form-control"></textarea>
</div>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question :</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
Thank you very much in advance.
Use AJAX in the html to call php.
HI all i've a basic Web Form for putting data into a mysql database, I created code to report if i was connected to my Database correctly and it was so on completion of the form i tested it and it seems to do what i expected but when i goto my database no data was actually entered?
my form
<form class="form-horizontal" name="myForm" method="POST" action="data.php" onsubmit="return(validate())">
<div class="container-fluid">
<div class="row">
<div class="col-md-5" style=" margin-left:5%">
<div class="form-group" >
<input type="text" class="form-control" name="Name" placeholder="Enter your name!">
</div>
<div class="form-group">
<input type="email" class="form-control" name="Email" placeholder="Enter email">
</div>
<div class="form-group">
<input type="password" class="form-control" name="Pass" placeholder="Enter password">
</div>
</div>
<div class="col-md-5" style="float:right; margin-right:5%">
<div class="form-group">
<input type="number" class="form-control" name="Num" onsubmit="return(phonenumber(myForm.Num))" placeholder="Enter phone no.">
</div>
<div class="form-group">
<input type="text" class="form-control" name="Comment" placeholder="Any comments?">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
data.php
<?
define('DB_NAME', 'Demo');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
if( $_POST )
{
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Demo", $con);
$Name1 = $_POST['Name'];
$Email1 = $_POST['Email'];
$Pass1 = $_POST['Pass'];
$Num1 = $_POST['Num'];
$Comment1 = $_POST['Comment'];
$Name = mysql_real_escape_string($Name);
$Email = mysql_real_escape_string($Email);
$Pass = mysql_real_escape_string($Pass);
$Num = mysql_real_escape_string($Num);
$Comment = mysql_real_escape_string($Comment);
$sql = "
INSERT INTO Demo ( `Name`, `Email`, `Password`,`Contact_num`,
`Comment`) VALUES ('$Name1',
'$Email1', '$Pass1', '$Num1','$Comment1'
)";
mysql_query($sql);
mysql_close($con);
}
?>
<?php
$dbhost = "localhost";
$dbuser = "root";
$conn = mysql_connect($dbhost , $dbuser);
mysql_select_db("Demo",$conn);
$Name1 = $_POST['Name'];
$Email1 = $_POST['Email'];
$Pass1 = $_POST['Pass'];
$Num1 = $_POST['Num'];
$Comment1 = $_POST['Comment'];
echo $Name1.$Email1.$Pass1.$Num1.$Comment1; //this is to check whether you are getting all the values or not.
$sql = "INSERT INTO TABLENAME ( `Name`, `Email`, `Password`,`Contact_num`, `Comment`) VALUES ('$Name1',
'$Email1', '$Pass1', '$Num1','$Comment1'
)";
mysql_query($sql);
mysql_close($con);
}
?>
Kindly consider that the Insert Query should have the name of the table, not the database.
So this is the PHP code that processes the form info and it supposed to send data into the DB. It is successful every time and shoots me a success message but when I look in database I see a new row but no actual data from the form.
REMINDER: the db connection is working, except it's sending blank values to fill up the table as opposed to the form data.
Here is the HTML form to be handled by the PHP code in dealer.php:
<form action="dealer.php" method="POST">
<div class="form-group">
<label for="company">Company Name</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Company Name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="Location">
</div>
<div class="form-group">
<label for="founded">Founded</label>
<input type="text" class="form-control" id="founded" name="founded" placeholder="Founded">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text" class="form-control" id="employees" name="employees" placeholder="# of employees">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
</div>
<div class="radio">
<label><p>Is the company traded publicly?</p>
<input type="radio" name="optionsRadios" name="public" id="Yes" value="Yes">
Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" name="public" id="No" value="No">
No
</label>
</div>
<div class="form-group">
<label class="sr-only" for="gross_2014">Gross Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="gross_2014" name="gross_2014" placeholder="Gross Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="net_2014">Net Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="net_2014" name="net_2014" placeholder="Net Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="growth_2014">Growth(%)</label>
<div class="input-group">
<div class="input-group-addon">%</div>
<input type="text" class="form-control" id="growth_2014" name="growth_2014" placeholder="Growth %">
<div class="input-group-addon">.00</div>
</div>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="customer" name="customer">Customer profile info... </p>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="products" name="products">Info about product offerings.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here are the contents of dealer.php that process the HTML form above:
<?php
$servername = "XX.XXX.XXX.XX";
$username = "smartkrawl";
$password = "Bondurant15!";
$dbname = "smartkrawl";
class companyInfo{
public $name;
public $location;
public $founded;
public $employees;
public $sales;
public $gross_2014;
public $net_2014;
public $growth_2014;
public function __construct($name,$location,$founded,$employees,$sales,$gross_2014, $net_2014, $growth_2014) {
$this->name = $name;
$this->location = $location;
$this->founded = $founded;
$this->employees = $employees;
$this->sales = $sales;
$this->gross_2014 = $gross_2014;
$this->net_2014 = $net_2014;
$this->growth_2014 = $growth_2014;
}
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014)
VALUES ('$name', '$location', '$founded', '$employees', '$sales', '$gross_2014', '$net_2014', '$growth_2014')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
You didn't get the POST values in your php code, that's why the columns of the row are empty. The variables are not set.
I don't think you should use a class just to handle a form, it's unnecessary.
Since you getting this data from a form, it's good to security the use of prepared statements to insert the data. You're already using PDO, so you can just use the prepared statements without problem.
You can read about PDO Prepared Statements on PHP Manual (http://php.net/manual/en/pdo.prepared-statements.php)
I modified your code and now should be working.
<?php
$name = $_POST['company'];
$location = $_POST['location'];
$founded = $_POST['founded'];
$employees = $_POST['employees'];
$sales = $_POST['sales'];
$gross_2014 = $_POST['gross_2014'];
$net_2014 = $_POST['net_2014'];
$growth_2014 = $_POST['growth_2014'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bindValue(1, $name);
$sql->bindValue(2, $location);
$sql->bindValue(3, $founded);
$sql->bindValue(4, $employees);
$sql->bindValue(5, $sales);
$sql->bindValue(6, $gross_2014);
$sql->bindValue(7, $net_2014);
$sql->bindValue(8, $growth_2014);
$exec = $sql->execute();
if($exec) {
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
By the way, in your HTML code, there's a quote missing on this line after the type attribute.
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
Replace by
<input type="text" class="form-control" id="sales" name="sales" placeholder="2014 sales">
And there's a field on the form that you didn't set on your PHP code, which is the optionsRadios radio. I didn't put that radio in the code because you didn't put it on the original code. So, if you want to put it there, just add it on the PHP like any other field.