PHP/PDO: Insert data into foreign column - php

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?

Related

Inserting HTML form data comes up blank

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')";

How can I update my entries with pdo::FETCH_CLASS and query it into my database?

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>

Inserting steam user info in db

Im trying to insert the steamid , steam real name . steam name into my db when the user login in my website
mycode :
<?php
if (isset($_GET['login'])){
$steamids= $steamprofile['steam_steamid'];
$name = $steamprofile['personaname'];
$real = $steamprofile['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
$button = "<a href='?login'><img src='http".(isset($_SERVER['HTTPS']) ? "s" : "")."://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_".$button[$buttonstyle].".png'></a>";
When the user log in i dont get anything in the db .
i tried to store the user info using sessions and it works but alway duplicate the value
the code is a little bit messy Because im still learning
Any Idea?
<?php
$db = array("DB_HOST"=>"localhost","DB_USER"=>"root","DB_PASS"=>"mysql","DB_NAME"=>"databasename",);
foreach ($db as $key => $value)
{
define($key , $value);
}
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (!$connection)
{
die ('<h1>connecting failed</h1>');
}
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection , $query);
if ($insert_query) {
echo "User added";
}else{
die("we have error " . mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit" name="login"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
check it we have create data base and check my code it work my table user have
steamid (varchar 255)
steamname (varchar 255)
steamreal (varchar 255)
user_logindate (Date)
i don't saw your HTML Form but i added and i think its work check this
<?php
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
you can add your src in image tag just copy and paste it in image Tag

Insert formfields to SQL - Error

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">

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))

Categories