MySQLi Insert into inserts 0? - php

I have a form on my website that submits data to my (mysql) database. This is done via Mysqli. After submission of the form I get the message:
"inputoftextboxhere" has been added to the database!.
But when I look in my database there is only a value of 0.
insert.php
<?php
//config bestand ophalen.
require_once 'config.php';
if(isset($_POST['submit']))
{
$email = $mysqli->real_escape_string($_POST['email']);
$sql = "INSERT INTO maillist (id, email) VALUES ('', '$email')";
if ($mysqli->query($sql))
{
echo "<center><div class='alert alert-success' role='alert'>".$email." is succesvol toegevoegd aan de database!</div></center>";
}
else
{
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
}
?>
Index.php
<form action="insert.php" method="post" accept-charset="utf-8" class="form" name="submit">
<legend>Email </legend>
<input type="text" name="email" value="" class="form-control input-lg" placeholder="E-mail" /><br />
<button class="btn btn-lg btn-primary btn-block signup-btn" name="submit" type="submit">Voeg nummer toe</button>
</form>
Screenshot of database:
https://gyazo.com/9ec48d3ce4ec6643d8fbcb2f3db42052

Please make sure the datatype of the email column in your database table is text or varchar. If it is set to integer or double probably that might be the issue.

Make sure that the database can store strings, so pick Varchar.
When it is set too boolean/bit or any number-based datatype your database doesnt now how to handle a string input.
Otherwise, debug the value that is getting posted to make sure you aren't just putting a zero in your database.

Related

SQL insert statement with user input to Phpmyadmin isnt working

I was trying to make a site and people could sign up/subscribe and i would store their email adresses in a database. I searched online for a solution but couldnt find anything
My code:
<html>
<?php include_once('include/html/hoofd.php') ?>
<body>
<h1 id="css"> ----- </h1>
<br><br><br>
<ul>
<form method="post" action="./emailverwerk.php" class="email" id="css2">
<b><extra space >Register and we will notify you with the the next GREAT deal!</b><br>
<br>
Full Name: <input type="text" class="css2" name="naam" placeholder="Full name"><br>
Email adress : <input type="email" class="css2" name="emailaddress" placeholder="Email Adress"><br>
Email adress : <input type="email" class="css2" name="Emailaddressrepeat" placeholder="Repeat Email "><br>
<a href="http:/----------/emailverwerk.php"><input type ="Submit" value ="Subscribe" id="css3"><br>
<?php
session_destroy();
if (isset($_SESSION["error"])) {
print ($_SESSION["error"]);
}
?>
</form>
</ul>
<ul>
<form method="post" class="actie" id="expired1">
<b>- Claim your free 1000 TRX here!!</b><br>
This is a one time offer! <br>
Click the link below and fill in your details to claim your free 1000 TRX!<br>
<input type="submit" value="Expired!!" id="css3">
</form>
</ul>
</body>
</html>
And my SQLI code :
<?php
session_start();
include_once ("include/database.php");
$name = $_POST["naam"];
$email = $_POST["Emailaddress"];
$emailherh = $_POST["Emailaddressrepeat"];
$sql = "INSERT INTO emaillist (naam , email)
VALUES ('".$_POST["naam"]."','".$_POST["emailaddress"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
Im a first year student as well so my programming experience isnt that big and perfect yet.
You must escape the strings. Else you are disallowing Irish. Think what happens with O'Brian. It will give you a mysterious "syntax error".
Your Anchor tag is not needed around the form submit, and it was not closed .

Attempting an INSERT INTO query with a form and php but database is not updating the record

I have an activity table which i want the users to be able to add data to it from my website. I have a Form and an INSERT INTO Query but when i click submit button the form clears but the database does not have the inputted record. I think the issue is that one of the fields (activity_cat) is a FOREIGN KEY on the table I'm trying to insert to.
<form>
<form action="" method="post">
Activity Category: <input type="text" name="activity_cat" /><br><br>
Activity Name: <input type="text" name="activity_name" /><br><br>
Activity Address: <textarea name="activity_address"> </textarea><br><br>
Activity Description: <textarea name="activity_description"> </textarea><br><br>
<input type="submit" name="submit"/>
</form>
The above form is my html form and the below is my php code to insert into the database
<?php
$conn = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
if (!$conn) {
die(mysqli_error());
}
if(isset($_POST["submit"])){
$sql = "INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`)
VALUES ('".$_POST["activity_cat"]."','".$_POST["activity_name"]."','".$_POST["activity_address"]."','".$_POST["activity_description"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
?>
The "activity_cat" is a Foreign Key in the "activity" table. This is so the activities are categorised into different categories. Im not sure if this is the problem or not. I am entering the exact activity_cat records that are in categories table but still no luck. Ideally i would like a drop down menu which the user can select the category type for the option in the form. Any help with this would be appreciated. I am new to coding, especially PHP and mysql. Any other information needed please ask
Thank You
You need to include a name attribute on your submit button.
Add name='submit'
On your submit button
Apart from the fact that your code is prone to SQL Injection attacks, you are checking if submit is set, when you did not provide a name for your button.
Add a name attribute to your input tag like so:
<input type="submit" name="submit" />
First, you have an un-closed form tag:
<form> <!-- What is this -->
<form action="" method="post">
Second, (and this is what's causing the problem in this case):
You did not specify an action to your form! The action attribute must be set to the path of the php file which holds your script, which inserts stuff into your database.
For example:
something.html:
<form action="inserter.php" method="post">
Activity Category: <input type="text" name="activity_cat" /><br><br>
Activity Name: <input type="text" name="activity_name" /><br><br>
Activity Address: <textarea name="activity_address"> </textarea><br><br>
Activity Description: <textarea name="activity_description"> </textarea><br><br>
<input type="submit" name="submit"/>
</form>
inserter.php:
<?php
$conn = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
if (!$conn) {
die(mysqli_error());
}
if(isset($_POST["submit"])){
//You don't need to concatenate, you can just put the variables directly into a string (which are double quoted) like this: ${variable's_identifier}
$sql = "INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`)
VALUES ('${_POST["activity_cat"]}','${_POST["activity_name"]}','${_POST["activity_address"]}','${_POST["activity_description"]}')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
//You SHOULD close the connection when you are done!
mysqli_close($conn);
?>
However, please do use parameterized prepared statements!
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
$stmt = $conn->prepare("INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $_POST["activity_cat"], $_POST["activity_name"], $_POST["activity_address"], $_POST["activity_description"])
$stmt->execute();
$stmt->close();
$conn->close();

PHP Post Echo Two Sql Entries

I need help figuring out why I receive two entries into my database with the following code. At this time it is inputting the complete record and a blank record into the database. Not sure why. Can anyone point me in the right direction of where I am going wrong? Thanks.
Form and PHP Code
<form method="post" action="cu.php">
<input type="text" name="name" value size="35"
placeholder="Name">&nbsp&nbsp
<input type="text" name="email" value size="35" placeholder="Email">
<br><br>
<select name="dropdown">
<option value="0">Comment Type</option>
<option value="A">Accounting</option>
<option value="FAQ">FAQ</option>
<option value="GQ">General Question</option>
<option value="TS">Technical Support</option>
</select>
<br><br>
<textarea name="comments" rows="10" cols="60" style"border: 3px solid #555"
placeholder="Comments"></textarea>
<br><br>
<input type="submit" value="Submit" id="btn">
<input type="reset" value="Reset" id="btn">
</form>
</one>
</div>
<?php
if ($_POST) {
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b>$name</b>";
echo "<br>You can use the following form again to enter a new name.";
}
$con = mysql_connect("mysql", "username", "pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
/* Prevent duplicate submissions */
if (isset($_COOKIE['FormSubmitted'])) {
show_error('You may only submit this form once per session!');
}
mysql_select_db("communication", $con);
$sql = "INSERT INTO contact (name, email, cusno, dropdown, comments)
VALUES
('$_POST[name]', '$_POST[email]', '$_POST[cusno]', '$_POST[dropdown]',
'$_POST[comments]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
That is because, everytime the page load, php will run your sql insert code. This happen because you don't check if the form is submitted, then run the sql query.
Do like this:
add name to your submit button:
<input type="submit" value="Submit" id="btn" name="submit">
then in php, wrap the sql insert in if statement
// check if submit button is POST, then run query
if(isset($_POST['submit']))
{
$sql = "INSERT INTO contact (name, email, cusno, dropdown, comments)
VALUES
('$_POST[name]', '$_POST[email]', '$_POST[cusno]', '$_POST[dropdown]',
'$_POST[comments]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
}
Update this lines
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
to
if (!empty($_POST) && !mysql_query($sql, $con) ) {
die('Error: ' . mysql_error());
}
Also i suppose that you browser requesting favicon file and the fore your code can be executed twice

How to disable writing to database if i made duplicate entry, and show warning in alertbox?

I am a bit new with php, so I need help. On one page i have small form with firstname and lastname fields. On submit i send it to external .php script where i want to check if there is already person with same name in database. If there is already person with entered name in database, I want to cancel writing to database, and return to the html page. I have done this, but I want to display the JS messagebox "Person with this name already exists in db!", and if the writing to base was canceled, i want my input fields show last written values. I've been reading a lot of litertaure, and I'm lost. Thanks for help anyway :)
This is my form:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
My php code:
<?php
$con=mysqli_connect("localhost","root","","phptest");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
}
if (isset($_POST['lastname'])) {
$lastname = $_POST['lastname'];
}
$duplicate=mysqli_query($con,"SELECT * FROM persons WHERE FirstName='$firstname'");
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
header( 'Location://localhost/ivanda.php' ) ;
mysqli_close($con);
?>
This line:
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
Change it to this this code:
if(mysqli_num_rows($duplicate)>0)
{
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php'); </script>"; //add this line instead of header
}
-------------------------EDITED----------------------------------
Trys this:
$duplicate=mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='$firstname' limit 1");
if(mysqli_num_rows($duplicate)>0)
{
$row = mysqli_fetch_assoc($duplicate);
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php?firsName=".$row['FirstName']."&lastName=".$row['LastName']."'); </script>"; //add this line instead of header
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
With this you are sending the var via GET on the url...then in your form you should have something like this:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname" value="<?php if(isset($_GET['firsName'])){echo $_GET['firsName'];} ?>">
Lastname: <input type="text" name="lastname" value="<?php if(isset($_GET['lastName'])) {echo $_GET['lastName'];} ?>">
<input type="submit">
</form>
PS: Go for mysqli o PDO, remember it...mysql extension is gonna be deprecated soon
Saludos.

Trying to write to a MySQL database with a PHP form

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Categories