I'm trying to learn how to make a registration form. I was getting an error message: "PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'firstname' cannot be null"
Someone told me I could fix it with AJAX, which is something I want to learn anyway. But I'm not sure what I'm doing.
First, I took the PHP code out of my main page (register.php) and put it in a new file (reg-code.php). Then I included reg-code.php in register.php.
Next, I put the following in the head section of register.php:
<script>
submitHandler: function(form) {
$.post(
'/test/register/reg-code.php',
$(form).serialize(),
success: function() {
// display success message or something
It works!
}
);
};
</script>
I fixed one syntax error, but I get another one on the line success: function() {
But I'm not even sure if I'm moving in the right direction. The tutorials are confusing.
This is the PHP code I put in a separate file:
try {
$sql = "INSERT INTO members (firstname, lastname, username, password, password_confirm, email, age) VALUES (:firstname, :lastname, :username, :password, :password_confirm, :email, :age)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_GET['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_GET['lastname'], PDO::PARAM_STR);
$query->bindParam(':username', $_GET['username'], PDO::PARAM_STR);
$query->bindParam(':password', $_GET['password'], PDO::PARAM_STR);
$query->bindParam(':password_confirm', $_GET['password_confirm'], PDO::PARAM_STR);
$query->bindParam(':email', $_GET['email'], PDO::PARAM_STR);
$query->bindParam(':age', $_GET['age'], PDO::PARAM_STR);
$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
Do I just have to figure out a syntax error, or do I need to go back to square one?
That error message means that the firstname variable is not being passed in properly. Make sure the name/id of your form field is indeed "firstname".
actually there is no problem with your procedure but
In your members table firstname column is not null and you are passing null value to it
If you use jQuery $.post - then in your php-script you should use $_POST variables:
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
// etc
Also:
success: function() {
// display success message or something
It works! // this string will cause syntax error
}
Use standard alert() function:
success: function() {
// display success message or something
alert('It works!');
}
First of all, Ajax has nothing to do with that error you get! So you might wan't to consider changing your title.
But anyway.
This means that your $_GET['firstname'] doesn't have a value, which means that no input from your registration form is send trough to your code.
And my suggestion would be that you change all you $_GET varibles to $_POST['inputfieldname'].
Because if you are using a form to send the data, you can't access them trough GET, as GET is used to acces data sent via the URL, so let's say you sent something with the url, and the url was www.yoururl.com/sent.php?something=bla
You would get the value from "something" like so $_GET['something'] and that would now have the data "bla", just to clarify.
The reason it says that the column cannot be null, is because that you have set that rule in your database, and if you removed that, i would just be a blank field.
Hope it helps a bit.
Related
When I send my content from my frontend it successfully reaches my if (!empty)-statement but the table in my phpmyadmin/mysql-database does not recieve the information and does not add it.
I have two tables. One varchar (text) named "photo" and a ID called "id" which is A_I.
With my current code I only send (well attempt to send) the text about "photo" but nothing about the ID as it is A_I? Maybe I need to add some addiotional code to that as well and that might be the issue here and the reason the database does not seem to add the content that I send?
<?php
$value = json_decode(file_get_contents('php://input'));
$mysql_pekare= new mysqli ("", "","", "");
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value['photo']);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
?>
In my frontend when I send the content I recieve this in the log:
{"photo":"test"}
And I also recieve this in the log, the echo call I did if it reaches the IF function which it successfully does:
"You reached the IF-statement"
By default, json_decode() returns an object, so your value is in $value->photo.
So your INSERT code should be -
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value->photo);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
you must put the value for mysqli constructor required like localhost or ip , username of database , password of your database and database name then it will work fine for Example:-
$mysql_pekare=new mysqli ("localhost", "username","password", "databasename");
I am trying to post data to my url but the form is not recognising anything being posted.
http://localhost/webpanel/createkeys.php?pcname=joe&username=guessme
so surely in the code below the $post values should be stored?
$_POST['pcname'];
$_POST['username'];
But when I load that url I posted I get this error:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'pcname'
cannot be null' in
The rest of the code is posted below, it is a short php file but cannot work out the issue.
<?php
// if(!isset($_POST) || empty($_POST['pcname'])) {
// exit;
// }
$pcname = $_POST['pcname'];
$username = $_POST['username'];
include 'db.php';
$stmt = $connection->prepare('INSERT INTO dummy (pcname, username, privatekey) VALUES (?, ?, ?)');
$stmt->execute([
$pcname,
$username,
$privatekey
]);
You have to use $_GET instead of $_POST :
$_GET['pcname'];
$_GET['username'];
$_GET, you bold use $_REQUEST which holds both but this is commonly bad practice.
You can simulate $_POST by performing a Curl request within php.
http://php.net/manual/en/book.curl.php
I just finished my first working registration form connected to a database. Actually, it's basically a copy of a tutorial demo # http://jqueryvalidation.org/files/demo/milk/ except I had to add the database stuff.
I still have one minor bug. The form doesn't work unless I delete this code:
// specifying a submitHandler prevents the default submit, good for the demo
submitHandler: function() {
alert("submitted!");
},
It's kind of trivial, but it would be nice if the user could see some sort of "Success" message when they click the Submit button. I didn't want to post all the code, but I have a live page # http://www.govwa.org/test/registration.php
This is the PHP code that I inserted just before the form closing tag:
include('config.php');
$pdo = connect();
// adding new member using PDO with try/catch to escape the exceptions
try {
$sql = "INSERT INTO g1_members (firstname, lastname, username, password, password_confirm, email) VALUES (:firstname, :lastname, :username, :password, :password_confirm, :email)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$query->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$query->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$query->bindParam(':password_confirm', $_POST['password_confirm'], PDO::PARAM_STR);
$query->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
Does anyone have a hunch what the problem might be? Alternatively, is there another way of displaying a message when someone clicks the Submit button?
The submitHandler replaces the default submit, so the form is never submitted when you add that handler, you have to do it manually.
From the documentation
Callback for handling the actual submit when the form is valid. Gets
the form as the only argument. Replaces the default submit. The right
place to submit a form via Ajax after it is validated.
either remove it, or submit the form once valid in the handler
submitHandler: function(form) {
alert("submitted!");
form.submit()
},
I'm just using PDO to insert customers into my table but it has been overcomplicated by something which is unexplainable by myself or other research.
It gives the error code: 00000 (which means that is a success, apparently) but no data was actually inserted into the database and the error is only supposed to be outputted if the query was a failure, but the error is.. success?
$insertUser = $database->prepare("INSERT INTO customer (Surname, Forename, AddressRow1, AddressRow2, AddressRow3, AddressRow4, PostCode, Telephone, mobileNumber, Email, assignedGarage)
VALUES (:surname, :forename, :addressrow1, :addressrow2, :addressrow3, :addressrow4, :postcode, :telephone, :mobilenumber, :email, :assignedgarage)");
$insertUser->bindParam(':surname', $_POST['surname']);
$insertUser->bindParam(':forename', $_POST['forename']);
$insertUser->bindParam(':addressrow1', $_POST['addressrow1']);
$insertUser->bindParam(':addressrow2', $_POST['addressrow2']);
$insertUser->bindParam(':addressrow3', $_POST['addressrow3']);
$insertUser->bindParam(':addressrow4', $_POST['addressrow4']);
$insertUser->bindParam(':postcode', $_POST['postcode']);
$insertUser->bindParam(':telephone', $_POST['telephone']);
$insertUser->bindParam(':mobilenumber', $_POST['mobilenumber']);
$insertUser->bindParam(':email', $_POST['email']);
$insertUser->bindParam(':assignedgarage', $_SESSION['garageId']);
if(!$insertUser->execute()) {
$err[] = $database->errorCode();
}
elseif ($insertUser->rowCount() == 1) {
$id = $database->lastInsertId();
echo "<script type=\"text/javascript\">
<!--
window.location = \"updateUser.php?id=$id\"
//-->
</script>";
}
if(count($err)) {
echo "<p style=\"color:red;\">The following errors were detected:</p><br/>";
foreach ($err as $key => $error) {
echo "<p style=\"color:red;\">$error</p><br/>";
}
}
I first started without defining all the columns I wanted to insert into but that didn't work so I predefined them.
My table in its early, rudimentary stages. I have my reasons for choosing varchars for mobile/telephone numbers.
Summarising, you have this:
$insertUser = $database->prepare(...);
if(!$insertUser->execute()) {
$err[] = $database->errorCode();
^^^^^^^^^
}
So you're calling PDO::errorCode() rather than PDOStatement::errorCode(). As the manual explains:
PDO::errorCode() only retrieves error codes for operations performed
directly on the database handle. If you create a PDOStatement object
through PDO::prepare() or PDO::query() and invoke an error on the
statement handle, PDO::errorCode() will not reflect that error. You
must call PDOStatement::errorCode() to return the error code for an
operation performed on a particular statement handle.
Depending on your needs and current code, you might also be interested in PDOStatement::errorInfo(), which provides error details in friendly format. And, of course, you can also instruct PDO to throw exceptions and get rid of manual error checking.
Try this instead and tell me what you find:
try{
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
$insertUser = $database->perepare("INSERT INTO customer (Surname, Forename, AddressRow1, AddressRow2, AddressRow3, AddressRow4, PostCode, Telephone, mobileNumber, Email, assignedGarage) VALUES (:surname, :forename, :addressrow1, :addressrow2, :addressrow3, :addressrow4, :postcode, :telephone, :mobilenumber, :email, :assignedgarage)");
$insertUser->execute(array(':surname'=>$_POST['surname'], ':forename'=>$_POST['forename'], ':addressrow1'=>$_POST['addressrow1'], ':addressrow2'=>$_POST['addressrow2'], ':addressrow3'=>$_POST['addressrow3'], ':addressrow4'=>$_POST['addressrow4'], ':postcode'=>$_POST['postcode'], ':telephone'=>$_POST['telephone'], ':mobilenumber'=>$_POST['mobilenumber'], ':email'=>$_POST['email'], ':assignedgarage'=>$_SESSION['garageId']));
if ($insertUser->rowCount() == 1) {
$id = $database->lastInsertId();
echo "<script type=\"text/javascript\">
<!--
window.location = \"updateUser.php?id=$id\"
//-->
</script>";} else{
//sum'n sum'n
}catch(PDOException $e){
echo 'Error occured'.$e-getMessage();
}
This is because the $database->errorCode(); will not work for operations not directly performed on DB handle as in your case (you used PDO->prepare()). In your case this error code is reffering to last successful query not the one you are trying to execute, hence the 0000 error code.
You most likely have an error in your params array (values that are passed from $_POST). Also when using bindParams method you should specify the type of variable that is expected by database.
I have 2 files in my directory: one is js/form-validation-reg.js and one is HTML/registeruser.php. The javascript file validates a form from another html file which I have already checked; all values are passed all the way till the ajax but the values does not seem to be send to registeruser.php to be send in my database.
form-validation-reg.js:
//data string creation
var dataString = 'name='+ name
+ '&pass=' + pass
+ '&nationality=' + nationality
+ '&contactno=' + contactno
+ '&dateofbirth=' + dateofbirth
+ '&eaddress=' + eaddress
+ '&address=' + address
+ '&gender=' + gender
+ '&monthlysub=' + monthlysub;
//ajax
$.ajax({
type:"POST",
url: "HTML/registeruser.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
no errors is displayed and i have also tried setting the url as "../HTML/registeruser.php" but it still doesn't work.
PHP file(NOTE:i have also made sure my database details are correct.):
$name = stripslashes(strip_tags($_POST['name']));
$pass = stripslashes(strip_tags($_POST['pass']));
$nationality = stripslashes(strip_tags($_POST['nationality']));
$contactno = stripslashes(strip_tags($_POST['contactno']));
$dateofbirth = stripslashes(strip_tags($_POST['dateofbirth']));
$eaddress = stripslashes(strip_tags($_POST['eaddress']));
$address = stripslashes(strip_tags($_POST['address']));
$gender = stripslashes(strip_tags($_POST['gender']));
$monthlysub = stripslashes(strip_tags($_POST['monthlysub']));
$mysqli = new mysqli("localhost", "root", "","testdb")or exit("Error connecting to the database.");
$stmt = $mysqli->prepare("INSERT INTO user
(name, password, nationality, contactno, dateofbirth, email, address, gender, monthlysub)
VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->execute();
$stmt->bind_param("sssssssss", $name, $pass, $nationality, $contactno, $dateofbirth, $eaddress, $address, $gender, $monthlysub);
$stmt->fetch();
$stmt->close();
$mysqli->close();
try:
success: success,
instead of :
success: success(),
Not sure if this might help, but your dataString variable looks like you're building it to go into a URL which would use get instead of post. It could be that your php script doesn't know how to parse what's getting passed to it because it's looking in the post variables instead. Since you're passing a password you wouldn't want to use get for security reasons though.
You need to be calling the $stmt->bind_param before the $stmt->execute();
If there is still an issue then you need to break it down to see what is given you the issue:
1) Ensure that the Javascript is getting called. Put an alert() in your Javascript and reload the page. If the alert pops up then your are fine there and you can rule out any include URL issues.
2) If you are using Firefox, install firebug and then hit F12 and view the console. You will see the HTML/registeruser.php getting called and you will also be able to see the parameters that are getting sent and other info. You can also do this in Chrome. If the URL is getting called and you are receiving a 200 response then there are no problems there and that is one more thing you can rule out.
3) At this point we have ruled out the Javascript and the Ajax call. So now we focus on the Database connection and then the SQL query. After your connection on the registeruser.php do a select statement of a table that you know has records, echo them out to ensure you definitely have a connection and that you are connected to the correct database.
4) Echo your SQL statement to ensure that it has all the parameters.
By the way, you should also check your error handling, instead of using exit you should be checking for the mysqli error so after the new mysqli call then add this:
if (mysqli_connect_errno()) {
printf("Error connecting to the database: %s\n", mysqli_connect_error());
exit();
}
You may use a library that does that automatically, like http://phery-php-ajax.net already do the bridge between jQuery and PHP automatically
phery.remote('registeruser', {
'name': name,
'pass': pass,
'nationality': nationality,
'contactno': contactno,
'dateofbirth': dateofbirth,
'eaddress': eaddress,
'address': address,
'gender': gender,
'monthlysub': monthlysub,
});
Phery::instance()->set(array(
'registeruser' => function($data){
$data = array_map('strip_tags', $data);
/* rest of mysql code */
return PheryResponse::factory(); // do any DOM manipulation, redirect, etc
}
))->process();