I have heard of this issue but can't seem to figure it out. I have the database and table names correct. I am not finding any errors and i even inserted a table myself on phpmyadmin that worked but when I tried to do it on my site it doesnt work. I even tested the connection..Not sure what to do now
Maybe someone can take a look at my code and see if they notice anything
<?php
if(mysql_connect('<db>', '<un>', '<pw>') && mysql_select_db('smiles'))
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
$insert = "INSERT INTO 'guestbook'VALUES('','$time','$guestbook_name','$guestbook_message')";
if($insert = mysql_query($insert)){
header('Location: '.$_SERVER['PHP_SELF']);
} else{
$errors[] = 'Something went wrong . Please try again.';
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
else {
'Fixing idiot';
}
?>
<hr />
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<p>Post Somethign</p>
<br />
Name:<br /><input type="text" name="guestbook_name" maxlength="25" />
<br />
Message:
<br />
<textarea name="guestbook_message" rows="6" coles="30"maxlength="255"></textarea>
<input type="submit" value="Post" />
</form>
Remove quotes from table name 'guestbook' and leave a space between it and values
Table name doesn't need quotes and supossing you're using id autoincrement, don't insert an empty string. So it should be:
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
Also, take a look at your $time value. What MySQL data type is?
After the insert, try to display the mysql error:
$conn = mysql_connect('<db>', '<un>', '<pw>');
mysql_query($insert)
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
EDIT: The hole snippet should be similar to:
<?php
$conn = mysql_connect('<db>', '<un>', '<pw>')
if( $conn && mysql_select_db('smiles')) //Note $conn
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
mysql_query($insert)
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
you can try below query for insertion:
$insert = "INSERT INTO guestbook VALUES('','{$time}','{$guestbook_name}','{$guestbook_message}')";
Related
I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}
Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....
I would like to write a logic for data validation before insert into database. If the data not valid, then it will prompt user errors, but then I facing problem which not the logic that I wish:
(1) Message "Data successfully inserted!" shown even the error checking message was prompt.
(2) Message "Data successfully inserted!" shown even no data was entered in the form then click submit.
How should I change the logic to the one that I wish to have?
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$comp_nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["comp_licensee_name"])) {
$compLicenseeNameError = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
//php code ends here
?>
<html>
<head>
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<div class="maindiv">
<div class="form_div">
<form method="post" action="compReg.php">
<span class="error">* required field.</span>
<br>
<hr/>
<br>
Company Name:<br><input class="input" type="text" name="comp_name" value="">
<span class="error">* <?php echo $comp_nameError;?></span>
<br>
Company Licensee:<br><input class="input" type="text" name="comp_licensee_name" value="">
<span class="error">* <?php echo $compLicenseeNameError;?></span>
<br>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
I'd accumulate the errors into an array, and proceed to the insert part only if it's empty:
$errors = array();
if (empty($_POST["comp_name"])) {
$errors[] = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$errors[] = "Only letters and white space allowed in the computer name";
}
}
if (empty($_POST["comp_licensee_name"])) {
$errors[] = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
if (!empty($errors)) {
echo "The following errors occurred:<br/>" . implode('<br/>', $errors);
exit();
}
// If we didn't exit, continue to the insertion code
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {
$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
// check boolean variable value
$is_valid = 1;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$validation_error = "Only letters and white space allowed";
$is_valid = 0;
}
}
if (empty($_POST["comp_licensee_name"])) {
$validation_error = "Company Licensee Name is required";
$is_valid =0;
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
if($is_valid == 1 ){
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
} else {
echo $validation_error;
die;
}
}
//php code ends here
?>
I am trying to display an error message if a user has not entered a email and not add a column to the table.
The php code sends the email & randomly generated Code to the database and then displays a message, but if their has been not been a email entered I am trying to get a message to ask for an email and not create a column until done so.
I have achieved this before with other data inputing but I am still new to PHP, I have checked for answers but cannot just find the simple fix which I know it is.
Any help or comments would be greatly appreciated, thanks (Y)
PHP:
<?php
if(!empty($_POST['email'])) {
?>
<p>Enter an email</p>
<?php
}
if(isset($_POST['send'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`)
VALUES ('$email', '$inviteCode') ");
if($query){
?>
<p> "Thank you"</p>
<?php
}
else{
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
}
} // end brace for if(isset($_POST['Login']))
// end brace for if(isset($_POST['Login']))
?>
I have achieved this before by putting the following at the top;
if (empty($_POST) === false) {
$required_fields = array('email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Please Enter All Information';
break 1;
}
}
}
The html code for the submit and email input tags are below:
<input type="text" placeholder="Email" name="email" />
<input type="submit" value="send" name="send" />
Add if(!empty($_POST['email'])) to the top of your logic, instead of isset($_POST['send']) unless you are doing something else with the post send value later in your logic. isset will be true if there is an empty string.
To understand why please see:
isset() and empty() - what to use
Edit:
<?php
if(!empty($_POST)){
if(!empty($_POST['email'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`) VALUES ('$email', '$inviteCode') ");
//you might want to consider checking more here such as $query == true as it can return other statuses that you may not want
if($query){
?>
<p> "Thank you"</p>
<?php
}
else{
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
}
}
else {
?>
<p>Enter an email</p>
<?php
}
}
?>
Try this:
<?php
// check if email is empty, if it is display this message
if(empty($_POST['email'])) {
?>
<p>Enter an email</p>
<?php
}
// else: the user entered something
else {
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`)
VALUES ('$email', '$inviteCode') ");
if($query){
?>
<p> "Thank you"</p>
<?php
}
else {
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
} // end else
} // end else
?>
I didn't notice it until I finished the validation but I realized that even when my errors appear on top of my form box I then go to phpmyadmin and I look at the data, and even if I purposely added errors the form will be submitted.
Then my second problem including the one stated above, no matter what I do the student Id or "anum" is not posting. it continues to give me a "0" value in the students table in my database.
This is the entire code:
<?php
//Starting session
session_start();
// Validation starts here
if (empty($_POST) === false) {
$errors = array();
$anum = $_POST['anum'];
$first = $_POST['first'];
$last = $_POST['last'];
$why = $_POST['why'];
$comments = $_POST['comments'];
if (empty($anum) === true || empty($first) === true || empty($last) === true) {
$errors[] = 'Form is incomplete please revise it!';
} else {
if (ctype_alnum($anum) === false) {
$errors[] = 'A number can only consist of alphanumeric characters!';
}
if ((strlen($anum) < 9) && (strlen($anum)) > 9) {
$errors[] = 'A number is incorrect!';
}
if (ctype_alpha($first) === false) {
$errors[] = 'First mame must only contain alphabetical characters!';
}
if (ctype_alpha($last) === false) {
$errors[] = 'Last name must only contain alphabetical characters!';
}
if (empty($why))
$errors[] = 'Please make sure to select the proper reasoning for your vistit today!';
elseif ($why === 'Other') {
if (empty($comments))
$errors[] = 'Please explain the nature of your visit in the comments box!';
else {
if (strlen($comments) < 15)
$errors[] = 'Your explaination is short, please revise!';
if (strlen($comments) > 45)
$errors[] = 'Your explaintion is to long, please revise!';
}
}
if (empty($errors) === false) {
header('location: signedin.php');
exit();
}
// Validations ends here
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = "testdbpass"; // Mysql password
$db_name = "test"; // Database name
// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=localhost;dbname=test;", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = $dbh->prepare("INSERT INTO `students` (anum, FIRST, LAST, why, comments)
VALUES (:anum, :FIRST, :LAST, :why, :comments)");
$query->execute(
array(
'anum' => $_POST['anum'],
'first' => $_POST['first'],
'last' => $_POST['last'],
'why' => $_POST['why'],
'comments' => $_POST['comments']
));
} catch (PDOException $e) {
error_log($e->getMessage());
die($e->getMessage());
}
$dbh = null;
}
}
?>
<html>
<body>
<title>Student Signin Form</title>
<table width="300" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<?php
if (empty($errors) === false) {
echo '<h3>';
foreach ($errors as $error) {
echo '<center><li>', $error, '</li></center>';
}
echo '<h3>';
}
?>
<form action="" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<tr colspan="3">
<center></center>
<strong>Student Signin Form</strong></tr>
<p>Student ID Number: <input type="text" name="anum" <?php if (isset($_POST['anum']) === true) {
echo 'value="', $_POST['anum'], '"';
} ?> />
<p>First Name: <input type="text" name="first" <?php if (isset($_POST['first']) === true) {
echo 'value="', $_POST['first'], '"';
} ?> />
<p>Last Name: <input type="text" name="last" <?php if (isset($_POST['last']) === true) {
echo 'value="', $_POST['last'], '"';
} ?> />
<p>How may we help you? <select name="why"/>
<option value=""></option>
<option value="Appeal">Appeal</option>
<option value="Other">Other: Please specify the nature of your visit bellow</option>
</select>
</tr>
<br>
<P>If other please describe the issue you are having.</P>
<textarea rows="10" cols="50" name="comments" <?php if (isset($_POST['comments']) === true) {
echo 'value="', $_POST['comments'], '"';
} ?>></textarea>
<input type="submit" name="submit" value="Send"/>
</form>
</table>
</body>
</html>
After more digging up and more understanding of what I was actually doing (the wrong way) I came up with my solution. Pretty much I had to make it so that the Mysql insert statements were a part of the error validation not stand-a-lone. If you look at my prior code the PDO statements had no real place in the code, it was just there. The cause of this was
if (empty($errors) === false) {
header('location: signedin.php');
exit();
}
What this was doing was even if there were errors I had to still redirect to the "signedin.php" that is not the desired affect. What had to be done was first change it from false to true.
if (empty($errors) === true) {
header('location: signedin.php');
exit();
}
Then after doing so you must then input your PDO statements in between the {}.
So then what this means is that if the script has picked up errors it will NOT run the PDO insert.
However if it is TRUE that there are no errors it will run the insert script with a error check for that script, then if it inserts correctly it will then redirect the user to the next page.
Example :
if (empty($errors) === true)
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="testdbpass"; // Mysql password
$db_name="test"; // Database name
$dbh = new PDO("mysql:host=localhost;dbname=test;", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$query = $dbh->prepare("INSERT INTO `students` (anum, first, last, why, comments)
VALUES (:anum, :first, :last, :why, :comments)");
$query->execute(
array(
'anum' => $_POST['anum'],
'first' => $_POST['first'],
'last' => $_POST['last'],
'why' => $_POST['why'],
'comments' => $_POST['comments']
));
}
catch (PDOException $e)
{
error_log($e->getMessage());
die($e->getMessage());
}
$dbh = null;
header('location: signedin.php');
exit();
}
Hopefully some one will find this of any use.
Well it looks like you are writing some code without actually testing it if it works or not. Take a look for example at these lines (around ca. line 50):
if (empty($errors) === false) {
header('location: signedin.php');
exit();
}
You are filling the $errors array with error messages. Then you're doing the redirect if there were errors. Doesn't make sense because this does also remove the error messages.