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))
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 created a page to insert element into a database in php.
At the beggining i start use with mySQL, and it works perfectly. Then I'm migrate to Postgres and so i had some problems.
I change my code and i don't receive erros,but when i'm trying to insert my elements into the db, this remains empty.
this the structure of my table Prenotazione
CREATE TABLE public."Prenotazione"
(
id integer NOT NULL DEFAULT nextval('"Prenotazione_id_seq"'::regclass),
nominativo character(20),
email character(20),
oggetto character(200),
nominativoi character(200),
nominativoe character(200),
emaili character(200),
emaile character(200),
data date,
orario_inizio time without time zone,
orario_fine time without time zone,
stanza integer
)
this is my index.php
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nominativo:<br> <input type="text" name="nominativo" placeholder="Nome Cognome" size="20"><br>
Email: <br> <input type="email" name="email" size="20" placeholder="email"><br>
Oggetto Conferenza:<br> <textarea name="oggetto" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
Data: <br> <input type="date" name="data" ><br>
Orario Inizio: <br> <input type="time" name="orario_inizio" min="09:30:00" max="16:30:00" ><br>
Orario Fine: <br> <input type="time" name="orario_fine" min="10:00:00" max="18:30:00"><br>
<br>
<b> Partecipanti Interni </b>
<br>
<br>
<div id="interni">
<div id="first">
Nominativo:<br> <textarea name="nominativoi" rows="5" cols="30" placeholder="Nome Cognome;" ></textarea><br>
Email:<br> <textarea name="emaili" rows="5" cols="30" placeholder="Inserire Email"></textarea><br>
<br>
<br>
</div>
</div>
<b> Partecipanti Esterni </b>
<div id="esterni">
<div id="first">
Nominativo:<br> <textarea name="nominativoe" rows="5" cols="30" placeholder="Nome Cognome;" ></textarea><br>
Email:<br> <textarea name="emaile" rows="5" cols="30" placeholder="Inserire Email"></textarea><br>
<br>
<input type="submit" value="Invia" >
</form>
And finally the input.php
$checkdata = "SELECT count(*) as prenotato
FROM Prenotazione
WHERE data='$data'
AND NOT ('$newTimeEnd' < orario_inizio OR orario_fine < '$orario_inizio')";
$querycheck = $dbh->prepare($checkdata);
$querycheck->execute();
$prenotato = $querycheck->fetch()[0];
var_dump($prenotato);
if ($prenotato == 0 AND $stanza == 0 ) {
$query1 = "INSERT INTO Prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',1)";
var_dump($query1);
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
else if ($prenotato == 1){
$query1 = "INSERT INTO Prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$orario_fine','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',2)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
I posted the part that are interesting to the problem.
Thanks
The result of var_dump is :
NULL string(269) "INSERT INTO Prenotazione
(nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza)
VALUES
('username','email#email.com','2018-10-03','09:30','12:30','object','username1','email1#email1.com','username2','email2#email2.com',1)"
The problem is with your table name in double quotes. Don't use double quotes, or use them in every request.
You can verify your code here:
http://rextester.com/VIEH75483
Also, see more: Omitting the double quote to do query on PostgreSQL
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">
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 !
For the last 5 hours I've been trying to figure out why this form won't insert data into MySQL when it seems to be correct.
Form
<form action="insertComment.php" method="POST">
<input type="hidden" name="article_id" value="<?php echo $article_uid;?>">
<input type="text" name="name" placeholder="Enter your name" required/>
<input type="email" name="email" placeholder="Enter your email" required/>
<textarea type="text" name="comment" placeholder="Join the discussion..." required></textarea>
<input type="submit" class="submit" value="Submit Comment"/>
</form>
then on comment.php
include '../../../libraries/phpClass/commentClass.php';
$commentClass = new commentClass();
if(isset($_POST['name']) AND isset($_POST['email']) AND isset($_POST['comment']) AND isset($_POST['article_id']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$article_id = $_POST['article_id'];
$data = $commentClass->insertComment($name, $email, $comment, $article_id);
}
and this is the public function..
public function insertComment($name, $email, $comment, $article_id)
{
$sth = $this->db->prepare("INSERT INTO articles_comment(name, email, comment, article_id) VALUES (:name, :email, :comment, :article_id)");
$sth->execute(array(
':name' => $name,
':email' => $email,
':comment' => $comment,
':article_id' => $article_id
));
}
from what I can see there isn't anything wrong and I haven't been able to see anything why it wouldn't insert the values.. there are no errors whatsoever either..