Okay, I've looked everywhere. To begin with I have a form, a newsletter, that users enter their email into. Once they hit submit it checks a php form that takes that email and inputs it into an SQL database that stores the email. The problem is I get this error when submitting the form
Error: INSERT INTO emails (email) VALUES (random#yahoo.com)
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 '#yahoo.com)' at line 2
No idea why it wont put it into the database. The form code is
<section>
<div class="mockup-content">
<div class="morph-button morph-button-inflow morph-button-inflow-1">
<button type="button"><span>Subscribe to our Newsletter</span></button>
<div class="morph-content">
<div>
<div class="content-style-form content-style-form-4">
<h2 class="morph-clone">Subscribe to our Newsletter</h2>
<form action="scripts/mailer.php" method="post">
<p><input type="text" class="button" id="email" name="email" placeholder="NAME#EXAMPLE.COM">
<div>We promise, we won't send you any spam. Just love.</div>
<input type="submit" class="button" id="submit" value="SIGN UP"></p>
</form>
</div>
</div>
</div>
</div><!-- morph-button -->
</div>
</section>
This is just the html data for the form, the php data is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysql";
$email = ($_POST["email"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO emails (email)
VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Can anyone explaine why this is?
You should use a tick (') when binding variables in a query:
$sql = "INSERT INTO emails (email) VALUES ('$email')";
It is okay not to use tick when the value of your variable you are trying to bind is an int.
The email is in varchar datatype . you need to put quotes on it
$sql = "INSERT INTO emails (email) VALUES ('".$email."')";
Related
I'm trying to register the e-mail entered in my form by users in my SQL table. but I'm not receiving any errors and the data are not saved either!
<?php
echo "I was here !!!";
if(!empty($_POST['mail']))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mailing";
echo "I was here !!!";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO contact VALUES ("","'.$_POST['mail'].'")';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
and my html code:
<div class="form">
<p>Rester notifié par toutes les nouveautés !</p>
<form method="post" action="index.php" class="mainform">
<div class="field"><input type="text" class="field" name="mail" /></div>
<div class="submit"><input class="submit" type="button" value="Envoyer" /></div>
</form>
</div>
can you tell me what's the problem ?
change your button type .because if you want to submit the data by form then button type should be submit like that
<input class="submit" type="submit" value="Envoyer" />
Check if there's a value for $_POST['mail']. Your condition didn't handle empty value for $_POST['mail']. If there is a value. Change your query
INSERT INTO contact(email) VALUES ("'.$_POST['mail'].'")
Try this. Since you only need to add an email. Hope it helps.
I have a form in HTML, but it's not setup like normal I guess. I'll post the code form the HTML (PHP) file and the php to send it to the db.
<form action="upload.php" method="POST">
<!-- Name input-->
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="">
<input id="name" name="name" placeholder="First and Last Name" class="form-control input-md" type="text" required>
</div>
</div>
<div class="form-group">
<label class=" control-label" for="supportingDoc">Upload Supporting Documentation</label>
<div class="">
<input id="supportingDoc" name="supportingDoc" class="input-file" type="file" style="margin-top: .5em; margin-left: 4em;">
</div>
</div>
<hr>
<!-- Submit -->
<div class="form-group">
<label class="control-label" for="submit"></label>
<div class="">
<button value="Submit" type="submit" id="submit" name="submit" class="btn btn-danger" style="border-radius: 25px;">Submit</button>
</div>
</div>
</form>
Here is my SQL/PHP
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect("localhost","xxx","xxx","xxx");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_REQUEST['name'])){
// set variables
$name = mysql_real_escape_string($_POST['name']);
$supportingDoc = mysql_real_escape_string($_POST['supportingDoc']);
$sql = "INSERT INTO `tablew` (name, supportingDoc) VALUES ('$name', '$supportingDoc')";
$result = mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
printf("New record created successfully");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
printf("Error: " . $sql . "<br>" . $con->error);
}
$con->close();
}
?>
I've tried all sorts of variations and nothing is showing in phpmyadmin. I've even replicated from a previous site I created and it still didn't work lol.
I see that there are variables for the login info and still put it in the mysqli, but I've been at this one thing for about 8 hours now and am out of juice, so hopefully someone sees what I messed up on.
Thanks in advance for any help everyone.
===========================================================================
UPDATE:
I made all the changes mentioned above and now get this:
Warning: mysqli_connect(): (HY000/1049): Unknown database
I can see the database in phpmyadmin and Sequel Pro. I've also made sure to set the password and login to 'root'. My code is as follows for login:
$con = mysqli_connect("localhost","root","root","epboarding");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and this is my POST:
if (isset($_REQUEST['submit'])){
// set variables
$name = mysqli_real_escape_string($con, $_POST['name']);
$sql = "INSERT INTO `wos` (name) VALUES ('$name')";
$result = mysqli_query($con,$sql);
Following issues can be there:
Uploading error. Use enctype="multipart/form-data" in form tag.
Correct Mysql_connect details i.e. Username, Password, Dbname.
mysql_real_escape_string is depricated. Use mysqli.
Recheck your column names i.e. name, supportingDoc.
Your html code wrong. Whenever you want to use input type file, you need to put <form> tag to <form enctype="multipart/form-data">. If you re not declaring the enctype, then the PHP cannot read the file.
you have to put
<form enctype="multipart/form-data">
when uploading file . correct your html.
Try This
The issue is after clicked on submit button it's not hitting the (isset($_REQUEST['name']))
Change it
if (isset($_REQUEST['submit'])){ //code here}
because you button name is submit.
Use SQL injection like
$con->real_escape_string($_POST['name']);
for the unknown database error. I simply went to operations in phpmyadmin and changed the name of the database and it worked. give it a try if you haven't fixed the problem yet.
in addition to #tbi
answer
Check php.ini for max post size it cause the POST request to fail if the size exceeds the size set in php.ini
post_max_size=20M
upload_max_filesize=20M
check your SQL connection and your permissions on the DB
use enctype="multipart/form-data" in your form only when you need to upload files (for security reasons)
finally, don't forget to bind your post params to prevent SQL-Injection
Params Binding
If you are using a default account on a local installation, then your connection code will probably look like this:
<?php $con = mysqli_connect('localhost','root','');
mysqli_select_db('epboarding', $con); ?>
use enctype="multipart/form-data" in form tag when you use file type.
<form name="" method="POST" action="" enctype="multipart/form-data">
3.change the following line
if (isset($_REQUEST['name'])){
to
if (isset($_REQUEST['submit'])){
correct the syntax when post data like mysql to mysqli.
From the PhpMyAdmin screenshot, it looks like the database is running on port 8889, meaning you would need:
$con = mysqli_connect("localhost","xxx","xxx","xxx", 8889);
In addition to what the others have said, I thought I'd provide a tidied script and some (hopefully) useful resource for you other issues.
http://php.net/manual/en/mysqli.construct.php
What's wrong with using $_REQUEST[]?
https://www.w3schools.com/sql/sql_injection.asp
As for your unknown database error this is either your database doesn't exist, is incorrectly named in your PHP script or is unavailable through localhost.
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error ) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
// Check if values are set with post rather than request, as this is deprecated and can output unexpected results
if ( isset( $_POST['name'] ) ) {
// Set variables
$name = $_POST['name'];
$supportingDoc = $_POST['supportingDoc'];
// Prepare a statement and bind parameters to prevent sql injection
$stmt = $conn->prepare( "INSERT INTO `tablew` (name, supportingDoc) VALUES (?, ?)" );
$stmt->bind_param( 'sb', $name, $supportingDoc );
if ( $stmt->execute() ) {
echo "New record created successfully";
printf( "New record created successfully" );
} else {
echo "Error: " . $stmt->error;
printf( "Error: " . $stmt->error );
}
$stmt->close();
$conn->close();
}
I want to go from a HTML form to a SQL database using PHP.
Here is my current code:
PHP:
if(isset($_POST['submitIpG']))
{
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ($_POST['submitIpG'])";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
echo "<br />\n";
}
As you can see it's hard coded with a specific IP. However, I want it to use an IP from the user input in my form.
HTML:
<form method="post">
<input type="value" name="submitIpG" value=""/>
<input type="submit" name="submitIpG" value="ADD"/>
</form>
How do I do this? I've tried things such as:
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpB']')";
Without success.
Thanks!
You should set the action php script in form html also your inputs should be like
<form method="post" action="your_php_file.php">
<input type="text" name="submitIpG" placeholder="the ip input"/>
<input type="submit" name="submit" value="ADD"/>
</form>
and your_php_file.php should be like
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpG']')";
But the most important part is DO NOT USE sql queries like that. Please consider using prepared statement.
There is a good and simple example at w3school. this is the link you may want. https://www.w3schools.com/php/php_mysql_prepared_statements.asp
What i was trying to do is , enter data in the text field click the " Track product" button and then verifying the value entered from a database and if the value exists, displaying some other data from the table in the same page.
Here is the code that i did:
<div class="wrapper col1">
<div id="container">
<form>
<h3>Enter Your Track_ID</h3><input type="text" name="trk_id">
<input type="submit" action="tracking.html" value="Track Product" name="track" method="post">
</form>
</div>
</div>
<div class="wrapper col2">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_drive2016";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT EMPLOYEE_ID,FIRST_NAME, LAST_NAME, EMAIL FROM employees WHERE EMPLOYEE_ID=$_POST['track']";
$result = mysqli_query($conn, $sql);
if($row[EMPLOYEE_ID]!=null){
echo $row[EMPLOYEE_ID].'</br>'.'<h2>'.'Your poduct is on Process'.'</h2>';
}
?>
</div>
And this the result i get -_-.
Lot of stuff might be wrong, take those into consideration.
I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}