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
?>
Related
No error messages appear on the page. Upload File button works. Upload button doesn't trigger db insert but the page refreshes as if it did.
I am not sure if the array of data from Excel is being coded correctly on the INSERT Into command. Any help is appreciated but PLEASE keep it simple. I am not a seasoned developer. Very green and primarily use procedural coding. If you use an experienced term, don't assume I know what it means.
PHP - if Post Submit button code. The errorMsg doesn't display if no file is attached and submit button is clicked
var_dump($_POST);
if (isset($_POST['submit'])) {
//print_r($_FILES);
$ok = 'true';
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
echo ++$x;
if ($handle !== FALSE){
$errorMsg = "<br /><div align='center'><font color='red'>Please select a CSV file to import</font></div>";
$ok = 'false';
echo ++$x;
PHP continued - I'm not seeing the uploaded file populate the database
} else {
print_r(fgetcsv($handle));
while(($filesop = fgetcsv($handle, 1000, ",")) !== FALSE){
$email = mysqli_real_escape_string($con_db, $filesop[0]);
$f_name = mysqli_real_escape_string($con_db, $filesop[1]);
$l_name = mysqli_real_escape_string($con_db, $filesop[2]);
$password = md5(mysqli_real_escape_string($con_db, $filesop[3]));
$zipcode = mysqli_real_escape_string($con_db, $filesop[4]);
$co_id = mysqli_real_escape_string($con_db, $filesop[5]);
$employee = mysqli_real_escape_string($con_db, $filesop[6]);
$assessment_ct = mysqli_real_escape_string($con_db, $filesop[7]);
echo ++$x;
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( strlen($email) > 0) {
echo ++$x;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo ++$x;
$ok = 'false';
$errorMsg .= 'E-mail address is not correct';
}
}
// error handling for password
if (strlen($password) >= 5) {
echo ++$x;
$ok = 'true';
} else {
echo ++$x;
$ok = 'false';
$errorMsg .= 'Your password is too short (please use at least 5 characters)';
}
// If the tests pass we can insert it into the database.
if ($ok == 'true') {
echo ++$x;
$sql = mysqli_query($con_db, "INSERT INTO `myMembers` (email, f_name, l_name, password, zipcode, co_id, employee, assessment_ct) VALUES ('$email', '$f_name', '$l_name', '$password', '$zipcode', '$co_id', '$employee', '$assessment_ct')") or die ("Shit is not working");
} else {// close if $ok == 'true'
$result = print_r($handle);
echo $handle.'<br>';
echo ++$x;
}
} // close WHILE LOOP
fclose($handle);
if ($sql !== FALSE) {
echo ++$x;
$successMsg = 'Your database has imported successfully!';
//print_r($_FILES);
//header('excel_import.php');
} else {
echo ++$x;
$errorMsg = 'Sorry! There is some problem in the import file.';
//print_r($_FILES);
//header('excel_import.php');
}
} // close if (!is_null($file)){
} // close if $post = submit
HTML Code for the form to submit uploaded file
<form enctype="multipart/form-data" method="POST" action="excel_import.php">
<div align="center">
<label>File Upload: </label><input type="file" id="csv_file" accept=".csv" >
<p>Only Excel.CSV File Import</p>
<input type="submit" name="csv_file" class="btn myButton" value="Upload">
</div>
</form>
</div>
<div><?php echo $errorMsg; ?><?php echo $successMsg; ?></div>
Your submit button does not have a name - and thus $_POST['submit'] is not set. Also, fclose($file) should be fclose($handle). And you should be checking with $handle !== FALSE and $sql !== FALSE rather than with is_null().
I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}
i am trying to write a simple chat script using php and mysql and i think i am returning the actual values of "Sender" and "Message" without ever getting the values of those columns. below is my index page where i am trying to display the queried results.
<?php
require('/includes/core.inc.php');
if (isset($_POST['send'])){
if(send_msg($_POST['sender'], $_POST['message'])){
echo "Message Sent";
}
else{
echo "message not sent";
}
}
?>
<div id ="messages">
<?php
$messages = get_msg();
$i = 0;
foreach($messages as $message){
$i = $i + 1;
echo '<strong>'.$message['sender'][$i].'Sent</strong><br/>';
echo $message['message'][$i].'<br /><br />';
}
?>
</div><!---Messages-->
<form action ="index.php" method="post">
<lable>Enter Name:<input type="text" name="sender"/></label>
<lable>Enter Message:<input type='text' name="message"></label>
<input type = "submit" name="send" value="send message">
</form>
and then here is my actual chat function. i know i am getting the values into and out of the database as i can check it through phpmyadmin but why isn't it displaying ont he page? thanks so much for any answer you may have for me ! sorry for bad english.
<?php
function get_msg(){
$query = "SELECT 'Sender', 'Message' FROM chat";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender'=>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message){
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO chat VALUES (null, '{$sender}','{$message}')";
if($run = mysql_query($query)){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
?>
$query = "SELECT 'Sender', 'Message' FROM chat";
should be
$query = "SELECT Sender, Message FROM chat";
In the first case you select the fixed strings Sender and Message because single quotes.
I have a basic Form that submits data into a database and I want it to require certain fields to be submitted, so far it recongizes that the fields are empty, but it still submits regardless. I can't seem to find a solution..
Code
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr;
$asin = $quantity = $floor = $location;
# this is processed when the form is submitted
# back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"]))
{$asinErr = "ASIN is required";}
else
{$asin = addslashes($_POST["asin"]);}
if (empty($_POST["quantity"]))
{$qtyErr = "Quantity is required";}
else
{$quantity = addslashes($_POST["quantity"]);}
if (empty($_POST["floor"]))
{$floorErr = "Floor is required";}
else
{$floor = addslashes($_POST["floor"]);}
if (empty($_POST["location"]))
{$locErr = "Location is required";}
else
{$location = addslashes($_POST["location"]);}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', now()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Amnesty Added - View it <a href=amnesty_log_summary.php>HERE</a></font></h3>";
}
?>
<form name="fa" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<table>
<tr><td>ASIN:</td><td><input type="text" name="asin" id="asin"><span class="error">* <?php echo $asinErr;?></span></td></tr>
<tr><td>Quantity:</td><td><input type="text" name="quantity" id="quantity"><span class="error">* <?php echo $qtyErr;?></span></td></tr>
<tr><td>Floor:</td><td><select name="floor"><option value="1">Floor 1</option><option value="2">Floor 2</option></select><span class="error">* <?php echo $floorErr;?></span></td></tr>
<tr><td>KIVA Floor:</td><td><input type="radio" value="Yes" name="location">Yes<input type="radio" value="No" name="location">No</select><span class="error">* <?php echo $locErr;?></span></td></tr>
<tr><td><input type="submit" name="submit" id="submit" value="Submit Amnesty!"></td></tr>
</table>
</form>
Updated:
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr = "";
$asin = $quantity = $floor = $location = "";
$lb_error = 0;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
if (empty($_POST["quantity"])) {
$qtyErr = "Quantity is required";
$lb_error = 1;
} else {
$quantity = addslashes($_POST["quantity"]);
}
if (empty($_POST["floor"])) {
$floorErr = "Floor is required";
$lb_error = 1;
} else {
$floor = addslashes($_POST["floor"]);
}
if (empty($_POST["location"])) {
$locErr = "Location is required";
$lb_error = 1;
} else {
$location = addslashes($_POST["location"]);
}
if($lb_error) {
continue;
}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', curdate()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
You want to check if you error variables are empty. If they are not, then break the script
ie
if(!empty($asinErr) || !empty($qtyErr) || !empty($floorErr) || !empty($locErr) ) {
break;
}
Something along these lines.
Check for the errors before you get to the point where you are writing to the database
Define at the top
$lb_error = 0;
Throughout your if/else checks for errors, if there is an error, assign the variable a 1
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
Then after you have completed all of these, do a check for errors and break if there are any
if($lb_error) {
break;
}
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}')";