Unable to insert datas in the database using PDO - php

I'd like to create a sign up form using PDO, but for an unknown reason, everything works excepted the writing into the database.
I'm quite stuck since Friday, and I'm kinda beginner in PDO, I believe I didn't saw something, but I can't tell what...
Any idea ?
<?php
include('bdd.php'); //Allows to connect to the db from an other file
?>
<form name="inscription" action="confirmation.php" method="POST">
<label for 'prenom'>Prénom: </label>
<input type="text" name="prenom" required placeholder="Prénom"/>
<label for 'nom'>Nom: </label>
<input type="text" name="nom" required placeholder="Nom"/>
<label for 'passe'>Mot de passe : </label>
<input type="password" name="passe" required/>
<label for 'confirm_passe'>Confirmez le mot de passe : </label>
<input type="password" name="passe" required/>
<label for 'email'>Email: </label>
<input type="email" name="email"/ required placeholder="Adresse e-mail">
<label for 'telephone'>Téléphone: </label>
<input type="telephone" name="telephone"/ required placeholder="ex: 0123456789">
<select name="fonction" id="fonction" required="required">
<option value="">Selectionnez votre fonction</option>
<option value="choix1">Présiden(e)</option>
<option value="choix2">Vice-Président(e)</option>
<option value="choix3">Administrateur</option>
<option value="choix4">Directeur/trice</option>
<option value="choix5">Travailleur social</option>
<option value="choix6">Secrétaire</option>
</select>
<input type="submit" value="send">
</form>
<?php
if(!empty($_POST['inscription'])){
if ( $_POST['confirm_passe'] != $_POST['passe'] ){
echo "Passowords don't match";
}
$req = $db->prepare('INSERT INTO inscrits (prenom, nom, passe, telephone, email, fonction, droits) VALUES(:prenom, :nom, :passe, :telephone, :email, :fonction, 0)');
$req->execute(array(
'prenom' => $_POST['prenom'],
'nom' => $_POST['nom'],
'passe' => $_POST['passe'],
'telephone' => $_POST['telephone'],
'email' => $_POST['email'],
'fonction' => $_POST['fonction'],
'droits' => $_POST['droits'],
));
}
?>
As you can see, I'm not english so please don't hesitate to ask any translation if you need to understand something :)
Thanks !

The keys from input_parameters must match the ones declared in the SQL.
see doc
try this:
edit for error message:
set:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
in your bdd.php file for pdo error handling.
then
try{
$req = $db->prepare('INSERT INTO inscrits (prenom, nom, passe, telephone, email, fonction, droits) VALUES(:prenom, :nom, :passe, :telephone, :email, :fonction, 0)');
$req->execute(array(
':prenom' => $_POST['prenom'],
':nom' => $_POST['nom'],
':passe' => $_POST['passe'],
':telephone' => $_POST['telephone'],
':email' => $_POST['email'],
':fonction' => $_POST['fonction'],
':droits' => $_POST['droits']
));
}
catch (PDOException $e) {
print $e->getMessage ();
die;
}

You are missing :droits (inside VALUES) inside prepare() function.
$req = $db->prepare('INSERT INTO inscrits (prenom, nom, passe, telephone, email, fonction, droits) VALUES (:prenom, :nom, :passe, :telephone, :email, :fonction, :droits)');
$req->execute(array(
'prenom' => $_POST['prenom'],
'nom' => $_POST['nom'],
'passe' => $_POST['passe'],
'telephone' => $_POST['telephone'],
'email' => $_POST['email'],
'fonction' => $_POST['fonction'],
'droits' => $_POST['droits'],
));
}

Ok so I finally managed to have something that is actually working, here is the code to have a sign up form that needs to be validated by an administrator if someone needs it in the future:
<?php
include('bdd.php'); //File that allows you to get connected to the server
if(!empty($_POST)){
// Form has been submitted
if ( $_POST['confirm_passe'] != $_POST['passe'] ) echo "Passwords don't match";
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
//
$req = $db->prepare('INSERT INTO your_table (table1, table2, table3, table4, rights) VALUES(:value1, :value2, :value3, :value4, :rights)');
$req->execute(array(
':value1' => $_POST['table1'],
':value2' => $_POST['table2'],
':value3' => $_POST['table3'],
':value4' => $_POST['table4'],
':rights' => 0
));
header('location:confirmation.php'); //Redirects you in a page that informs you that you are now registered
}
catch (PDOException $e) {
print $e->getMessage ();
}
}
?>
<!--And here goes the form that you can adapt at will -->
<form name="inscription" action="inscription.php" method="POST">
<label for="prenom">Prénom: </label>
<input type="text" name="prenom" required placeholder="Prénom"/>
<label for 'nom'>Nom: </label>
<input type="text" name="nom" required placeholder="Nom"/>
<label for 'passe'>Mot de passe : </label>
<input type="password" name="passe" required/>
<label for="confirm_passe">Confirmez le mot de passe : </label>
<input type="password" name="confirm_passe" required/>
<label for 'email'>Email: </label>
<input type="email" name="email"/ required placeholder="Adresse e-mail">
<label for 'telephone'>Téléphone: </label>
<input type="telephone" name="telephone"/ required placeholder="ex: 0123456789">
<select name="fonction" id="fonction" required="required">
<option value="">Selectionnez votre fonction</option>
<option value="choix1">Présiden(e)</option>
<option value="choix2">Vice-Président(e)</option>
<option value="choix3">Administrateur</option>
<option value="choix4">Directeur/trice</option>
<option value="choix5">Travailleur social</option>
<option value="choix6">Secrétaire</option>
</select>
<input type="submit" value="send">
</form>
Thank you for your help !

Related

PHP/PDO: Insert data into foreign column

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?

PDO - Insert blob image into MySQL

I have some problems
Notice: Array to string conversion in x\contact_ajouter_verif.php on line 17
This is my form :
<form action="contact_ajouter_verif.php" method="post" name="ajoutContact" enctype="multipart/form-data" >
<fieldset>
<label>Nom :</label> <input size="30%" type="text" placeholder="" name="nom" />
<label>Numéro :</label> <input size="30%" type="number" placeholder="" name="num" />
<label>Image au format png :</label><input type="file" name="img" />
</fieldset>
<input name="submit" type="submit" value="Ajouter"/>
</form>
And this is my pdo receiver page:
<?php
include('../inc/connexion.inc.php');
include('session.php');
$nom = $_POST['nom'];
$num = $_POST['num'];
$img = $_FILES['img'];
$pseudo = $user_check. "_contact";
$rqt1= "INSERT INTO $pseudo(CTC_NOM, CTC_NUMERO, CTC_IMG) VALUES(:nom, :num, :img)";
$result1 =$cnxpdo->prepare($rqt1);
$result1->execute(array(
'nom' => "$nom",
'num' => "$num",
'img' => "$img" //line 17
));
?>
I really don't understand what I'm doing wrong, please if someone have the solution :)
Finally found for those in the same case than me (unlikely but we never know...) :
<?php
include('../inc/connexion.inc.php');
include('session.php');
$nom = $_POST['nom'];
$num = $_POST['num'];
$img =addslashes(file_get_contents ($_FILES['img']['tmp_name']));
$pseudo = $user_check. "_contact";
$rqt1= "INSERT INTO $pseudo(CTC_NOM, CTC_NUMERO, CTC_IMG) VALUES(:nom, :num, :img)";
$result1 =$cnxpdo->prepare($rqt1);
$result1->execute(array(
'nom' => "$nom",
'num' => "$num",
'img' => "$img"
));
?>
Thanx for your help.

How to change div content in PHP?

I want to change the div's id intFrom. Content after inserting data to the database, I want the code not just echo ¡Enhorabuena!...
But replace the form with ¡Enhorabuena! I maybe, I could replace the form using AJAX.
Here is the code:
HTML
<form method="post" action="">
<div>
<select value="genero" name="genderselect" id="genero" required="required" autofocus="autofocus">
<option value="none" selected>- Selecciona Género - </option>
<option value="Mujer">Mujer</option>
<option value="Hombre">Hombre</option>
</select>
<input type="text" id="name" name="name" value="" placeholder="Nombre completo" required="required" autofocus="autofocus" />
<input type="email" id="email" name="email" value="" placeholder="Correo electrónico" required="required" />
</div>
<div>
<div class="infForm img">
<img src="http://www.miraqueguapa.com/Landings/General/img/biotherm.png" alt="Imagen Crema Aquasource Biotherm" class="biotherm">
</div>
<div class="infForm text">
<div class="legal">
<input type="checkbox" id="cblegales" value="1" name="cblegales" required="required" autofocus="autofocus">
<p>He leído y acepto la <a class="enlace_pp" href="http://www.miraqueguapa.com/content/5-privacidad-proteccion-datos" target="_blank">política de privacidad</a></p>
</div>
<input type="submit" value="ENVIAR DATOS" name="submit_form" style=" background-color: #DF2848;border: none;border-radius: 0px;color: white;width: 200px;float: right;padding-left: 50px;cursor: pointer;margin-top: -5px;" />
</div>
</div>
</form>
</div>
PHP
<?php
if (isset($_POST['submit_form'])) {
include 'connection.php';
$name=$_POST["name"];
$email=$_POST["email"];
$gender=$_POST["genderselect"];
if($gender=="none"){
echo"</br>";
echo"por favor selecciona nuestro género";
$link = null;
}
else{
$i=0;
$statement = $link->prepare("select email from webform where email = :email");
$statement->execute(array(':email' => "$email"));
$row = $statement->fetchAll();
foreach($row as $key) {
$i=$i+1;
}
if ($i !=0) {
echo" Este correo electrónico ya está registrado";
$link = null;
}
else{
$statement = $link->prepare("INSERT INTO webform(name, email, gender)
VALUES(:name, :email, :gender)");
$statement->execute(array(
"name" => "$name",
"email" => "$email",
"gender" => "$gender"
));
$link = null;
echo"¡Enhorabuena!"."<br/>";
echo"Tus datos se han enviado correctamente. A partir de ahora recibirás cada semana las últimas novedades y las mejores ofertas en Cosmética de las marcas más prestigiosas del mercado.";
}}}
?>
You need to add simple if else statement.
if (isset($_POST['submit_form'])) {
// Your code after form get submitted.
}
else {
// Show default form.
}
Just load your HMTL Code in to your PHP as a kind of "Template" with file_get_contents(__DIR__ . "Path/To/Your.html"); in to a variable and do a simple str_replace('id="your_element_id"', 'id="replace_id"', $template_variable); and echo your Template after if you just want to replace an ID.
If you want to change something within the Form, do it as i said above with str_replace('tag_you_are_looking_for', 'should_be_replaced_with', $template_variable);

MySQL PHP GAE Form

I have the following form:
<h2>Sign the Register</h2>
<form action="sign.php" method="post">
<div><textarea name="firstName" rows="3" cols="60" placeholder="First Name..." required="true"></textarea></div>
<div><textarea name="surname" value="mickey" rows="3" cols="60" placeholder="Surname..." required="true"></textarea></div>
<div><textarea name="course" value="mickey" rows="3" cols="60" placeholder="Your Course..." required="true"></textarea></div>
<div><textarea name="subject" rows="3" cols="60" placeholder="Subject..." required="true"></textarea></div>
<div><textarea name="level" rows="3" cols="60" placeholder="Level: C, I, H, M..." required="true"></textarea></div>
<div><textarea name="date" rows="3" cols="60" placeholder="Date.." required="true"></textarea></div>
<div><textarea name="time" rows="3" cols="60" placeholder="Time.." required="true"></textarea></div>
<div><input type="submit" value="Sign Register"></div>
And sign.php is (the connection is fine):
{
if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST)) {
$stmt = $db->prepare('INSERT INTO entries (firstName, surname, course, subject, level, date, time) VALUES (:firstName, :surname, :course, :subject, :level, :date, :time)');
$stmt->execute(array(':firstName' => htmlspecialchars($_POST['firstName']),
':surname' => htmlspecialchars($_POST['surname']),
':course' => htmlspecialchars($_POST['course']),
':subject' => htmlspecialchars($_POST['subject']),
':level' => htmlspecialchars($_POST['level']),
':date' => htmlspecialchars($_POST['date']),
':time' => htmlspecialchars($_POST['time'])));
$affected_rows = $stmt->rowCount();
}
}
$db = null;
?>
And when that is executed the user is taken to a following page which has the following:
<?php
try {
// Show existing entries.
foreach($db->query('SELECT * from entries') as $row) {
echo "<div><strong>" . $row['firstName'] . "</strong> wrote <br> " . $row['course'] . "</div>";
}
} catch (PDOException $ex) {
echo "An error occurred in reading or writing to register.";
}
$db = null;
?>
But the problem is that none of the records are showing on the success page. I am using google app engine with cloud SQL database (the connection is fine). It is basically a form, the user fills in the form and then the data is sent to the cloud sql database. Also once the user submits the form, they are taken to a page which displays the information that is just been submitted. Any easier/better ways of doing this are welcome.
Thank you
array_key_exists expects only two parameters (key,array) you should split
if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST))
into multiple conditions
if(array_key_exists('firstName', $_POST) && array_key_exists('surname', $_POST) ... array_key_exists('time', $_POST))

insert database nusoap-complexType

I want to create insert database a web service from :
http://www.discorganized.com/php/a-complete-nusoap-and-flex-example-part-1-the-nusoap-server/
Here's my script :
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', $in_contact);
if ($result){
echo "OK";
} else {
echo "Error";
}
?>
despite increasing ID, why the other columns remain empty ?
please help me, thank you.
The <form> code..
< form action="Contact.class.php" method="GET" > Nama Depan:<br> <input type="text" name="first_name"/><br> Nama Belakang:<br> <input type="text" name="last_name"/><br> Email:<br> <input type="text" name="email"/><br> Telepon:<br> <input type="text" name="phone_number"/><br><br> <input type="submit" value="Submit"/><br> < /form >
As you can see the method is GET , Change that to POST
Like this...
<form action="Contact.class.php" method="POST" >
The fixed <form> code.. You had a lot of indentations gone wrong..
<form action="Contact.class.php" method="POST" >
Nama Depan:<br> <input type="text" name="first_name"/><br>
Nama Belakang:<br> <input type="text" name="last_name"/><br>
Email:<br> <input type="text" name="email"/><br>
Telepon:<br> <input type="text" name="phone_number"/><br><br>
<input type="submit" value="Submit"/><br> </form>
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', array($in_contact));
if ($result){
echo "OK";
} else {
echo "Error";
}
?>

Categories