Simple PHP Form SQL Insert - php

I need some help with a very basic issue that I cannot resolve.
A bit of background: I have a PHP form and I would like the information inside the table to insert into my SQL table. For some reason, when I hit submit nothing inserts into the table and I have no idea why. Please help!
This is the PHP Code:
<?php
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
if(isset($_POST['submit'])) {
$result = mysql_query('INSERT INTO requests (song,name,dedicated,time) VALUES ("' . mysql_real_escape_string($_POST['name']) . '", "' . mysql_real_escape_string($_POST['dedicated']) . '", "' . mysql_real_escape_string($_POST['song']) . '", UNIX_TIMESTAMP())');
if ($result) {
echo 'Song requested successfully!<br />';
}
}
?>
This is the HTML Code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">Request:<br /><br />
Song:<br />
<input type="text" name="song"><br />
Name:<br />
<input type="text" name="name"><br />
Comments:<br />
<input type="text" name="dedicated"><br />
<input type="submit" name="submit" value="Submit" >
</form>
What this is meant to do is insert the request form into the SQL table, however nothing is happening. Any help is appreciated.
Kind Regards,
Edward

You can't mix mysql and PDO like that. You should use a PDO prepared query for the insert.
Also, the order of the values in the VALUES list have to match the column list -- you had the values in the order name, dedicated, song, time instead of song, name, dedicated, time.
<?php
if (isset($_POST['submit'])) {
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
$stmt = $db->prepare('INSERT INTO requests (song,name,dedicated,time) VALUES (:song, :name, :dedicated, UNIX_TIMESTAMP())');
$result = $stmt->execute(array(':song' => $_POST['song'], ':name' => $_POST['name'], ':dedicated' => $_POST['dedicated']));
if ($stmt->rowCount == 1) {
echo "Song requested successfully";
} else {
echo "Song could not be requested";
}
}

You should study about pdo and mysql and then use them ...
just see this simple example with mysql :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
and this one with pdo :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I prefer using pdo
Source : http://www.w3schools.com/php/php_mysql_prepared_statements.asp
NOTE : use prepared statements to avoid sql injection .

Related

How to query variable from database using php

Good Day developers outthere! 😊😊
I just wanna ask what is the problem with my code, I'm trying to make a webpage using html,css,php and database. Now I already created a php in my html form and my database is already connected, but everytime I submit the information in the html form I created, nothing appeared in my database.
<?php
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
echo "Successfully Added";
$sql= "INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, `Middle_Name') VALUES ('000',$FName,$MName)";
} else{
echo "<p>Insertion Failed.</p>";
}
?>
Just as #executable mentioned, you are defining query in your code but not executing it.
Define Connection Object (Mysqli, PDO..)
Prepare Query and Bind Variables
Execute your query
Here's an example using prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset($_POST['save']) ){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, Middle_Name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $transaction_number, $FName, $MName);
// set parameters and execute
$transaction_number = '000';
$FName= $_POST['FName'];
$MName= $_POST['MName'];
$stmt->execute();
echo "Successfully Added";
}else{
echo "<p>Nothing Posted</p>";
}
W3Schools and PHP.Net both have pretty good examples about how to use prepared statements to make your SQL Query more secure from SQL Injections.
You simply don't execute your query. Using MySQLi :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbthesis";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000', '$FName', '$MName')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Added";
} else {
echo "<p>Insertion Failed.</p>";
}
}
$conn->close();
You only making a query, not running query. This this code
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudioinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000','$FName','$MName')";
// code below runs your query
if (mysqli_query($conn, $sql)) {
echo "Successfully Added";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

MySQL error because of syntax in Custom PHP code

I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.

Submit post echo but does not write information in database

I'm having problem with updating information in database. The echo pops out as successful but the database row stays blank - why? PHP code:
<?php
if (isset($_POST['gender'])) {
// Sanitize and validate the data passed in
$gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
if ($stmt) {
$stmt->bind_param('s', $gender);
$stmt->execute();
$stmt->store_result();
if ($insert_stmt = $mysqli->prepare("INSERT INTO members gender VALUE ?")) {
$insert_stmt->bind_param('s', $gender);
}
}
echo "<div class='notemarg'> Your gender has been submitted</div>";
}
?>
and input form:
<form action="" method="POST">
<input type="radio" name="gender" value="male"> Male <br>
<input type="radio" name="gender" value="female"> Female <br>
<input type="submit" name="gender" value="Set gender" class="button">
</form>
I want to use mysqli->prepare to prevent SQL injection.
I fixed it with alternative way, where there is pre-defined input by button.
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "UPDATE members SET gender = '$gender' WHERE username = '".$_SESSION['username']."'";
if ($conn->query($sql) === TRUE) {
echo "<div class='notemarg'> Your gender has been submitted</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
And simple form:
<form action="" method="POST">
<input type="submit" name="Female" value="Female" class="button">
</form>
Thanks to all who wanted to help me, especially to anant kumar singh. I could not get that alter idea without his suggestions. Thanks!
UPDATE #1
It just pops out that echo "error"
<?php
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$stmt = $conn->prepare('UPDATE members
SET gender = ?
WHERE username = ?');
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
if ($conn->prepare === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
Don't know where is problem...
UPDATE #2
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
if ($mysqli->prepare($sql) === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
UPDATE #3
I added also some notes in code so
<?php
// I had here twice the ifisset here and
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//here the second one so I deleted that ifisset here...
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error; // This is the line that shows the error
}
$conn->close();
}
?>
I'm not sure what is problem... It pops the error on echo "No data supplied for parameters in prepared statement"
Following an answer being posted with a huge security vulnerability, it is worth taking a moment to fix this. There is a way to fix it so you can use your string concatenation approach, but it is generally not as good as parameterisation.
All you need to do is to take your working query, and convert it to a parameterised form. Something like this:
// Expects valid $mysqli object here
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
// ** As we discovered, the binding needs to happen in one
// ** call, not across several
$stmt->bind_param('ss', $_POST['Female'], $_SESSION['username']);
$stmt->execute();
Looking at your original code, there seems to have been two problems: the statement wasn't prepared at all (and so the program should have exited with a fatal error) and there was a syntax error in the original SQL statement.
In your new code, you're missing the execute() call.

SQL INSERT TROUBLE

I'm sitting infront of this code for 2 hours i cant figure out whats wrong :(
I've been trying to have a html form which calls the php function to insert the information from the form into the database but for some reason does not work :/
here is my form code :
<?php include 'connection.php'; ?>
<html>
<body>
<form action="user_create.php" method="POST">
username: <input type="text" name="username"/>
password: <input type="text" name="password"/>
email: <input type="text" name="email"/>
<input type="submit" name='submit' value="user_create"/>
</form>
</body>
</html>
database connection
<?php
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
?>
my php function
<?php include 'connection.php';?>
<?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$query = mysql_query("INSERT INTO users( username,password,email,type)
VALUES ('$username', '$password', '$email','1')");
mysql_query($query);
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else
{
echo '<script type="text/javascript">alert("jo");</script>';
}
?>
You should use PHP-PDO in order to avoid from SQL Injection attacks also it will fix insert trouble too.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$sql = "INSERT INTO users(username,
password,
email,
type) VALUES (
:username,
:password,
:email,
:type)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Are you connecting properly?
$dbuser = "";
Maybe must be "root" or other user?
Check this part :
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";

PDO Insert not working (PHP/MySQL)

After days of trial and error, I finally replaced my standard mysql code with PDO. Everything seems to be working just fine except for the last part where the app needs to INSERT user (name, email and time of signup) into database. After clicking submit, page just turns blank.
I don't see what is wrong with the code, so I would appreciate if you could help me out.
<?php
////Database connection values
$dsn = 'mysql:host=host; dbname=name; charset=utf8';
$db_user = 'username';
$db_pass = 'password';
//Database connection
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enable Exception error mode
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Use PDO safely = Turn off prepare emulation
// Databse connection check
if($db){
print "connected to the db " . "<br />";
}
//Declare values
$name = "";
$email = "";
$userMsg = "";
if ($_POST['name'] != "") {
$name = $_POST['name'];
$email = $_POST['email'];
//MySQL SELECT Query
$stmt = $db -> prepare ("SELECT * FROM newsletter WHERE email=?");
$stmt-> bindValue(1, $email);
$stmt -> execute ();
//Error - No email
if (!$email) {
$userMsg = '<br /><br /><h4><font color="FF0000">Please type an email address ' . $name . '.</font></h4>';
} // End email-input check
//Error - Email already in the system
else if ($stmt -> rowCount() > 0) {
$userMsg = '<br /><br /><h4><font color="FF0000">' . $email . ' is already in the system.</font></h4>';
} // End Row check
//OK - insert user into database
else {
$insert = $db -> prepare ("INSERT INTO newsletter (name, email, dateTime) VALUES(:name, :email, ,NOW())");
$insert -> execute(array(':name' => $name, ':email' => $email));
//Success! - Notify user
$userMsg = '<br /><br /><h4><font color="0066FF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
$name = "";
$email = "";
} // End INSERT
}
?>
VALUES(:name, :email, ,NOW())"
should be
VALUES(:name, :email, NOW())"

Categories