PHP Not Posting in SQL Database Insert Statement - php

So I'm attempting to gather data from a form in HTMl using the POST method and insert said data into a MySQL database using MySQLi functions. When in standalone PHP (without the database connection), I'm able to POST and echo data successfully to the second document.
However, once I open the connection to the database and attempt to use an insert statement, the data stops POSTing all together. I've tested the insert statement using strings, it works just fine.
Here's my form:
<form action="welcome" method="post">
First Name*<br>
<input type="text" name="userFN" required><br><br>
Last Name*<br>
<input type="text" name="userLN" required><br><br>
Email*<br>
<input type="email" name="userEmailAddress" required><br><br>
Password*<br>
<input type="password" name="userPassword" required><br><br>
Tell Us About Yourself<br>
<textarea rows="4" cols="50" name="userDescription">
</textarea>
<br>
<input type="submit">
</form>
Here's my PHP (welcome, as used in the action above).
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//post form info into variables
$userFN = mysqli_real_escape_string($conn, $_POST['userFN']);
$userLN = mysqli_real_escape_string($conn, $_POST['userLN']);
$userEmailAddress = mysqli_real_escape_string($conn, $_POST['userEmailAddress']);
$userPassword = mysqli_real_escape_string($conn, $_POST['userPassword']);
$userDescription = mysqli_real_escape_string($conn, $_POST['userDescription']);
$sql = "INSERT INTO users (userFN, userLN, userEmailAddress, userPassword, userDescription) VALUES" . " ('" . $userFN . "','" . $userLN . "','" . $userEmailAddress . "','" . $userPassword . "','" . $userDescription . "');";
echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
It always returns New record created successfully, and inserts a new record into the database, but all of the fields are blank. When I echo the insert statement, I get this:
INSERT INTO users (userFN, userLN, userEmailAddress, userPassword, userDescription) VALUES ('','','','','');
So it's clearly not getting my POST data anymore. I've tried using prepared statements and still no luck. What am I doing wrong here? I greatly appreciate any and all advice, thank you in advance.

The answer may surprise you.
So the issue is actually in the form "action". Because of the way my webhosting provider is configured, I actually needed to specify /index.php/ after the folder name in the action. It was actually confusing the server and for some reason translated to 'GET' instead of 'POST'. Hope this helps.
Thanks for all the support!

Related

php script to write to SQL database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to php and have written the following php script to write from a FORM. However, the database is not updating. I know that the database connection is okay. Any help would be appreciated.
$name = $_POST["name"];
$lastName = $_POST["last_name"];
$email = $_POST["email"];
$location = $_POST["location"];
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club.users (name, last_name, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
Try this
You have to use the SQL injection for security something like this
$conn->real_escape_string($_POST['name']);
Check your table name.I haven't use table name club.users before because it will display the error like table does't exist. Just use the table name club or users
Time to learn the PHP
https://www.w3schools.com/php/php_mysql_insert.asp
index.php
I hope your HTML code looks like this
<form action="register.php" method="POST" name="register">
<input type="text" name="name" placeholder="Name">
<input type="text" name="lastname" placeholder="Lastname">
<input type="email" name="email" placeholder="Email">
<input type="text" name="location" placeholder="Location">
<input type="submit" name="submit" value="Register">
</form>
Connection.php
If you are working on the local server the used root as username and password should be blank.
$servername = "localhost";
$username = "root";//if you are working on local server
$password = ""; //set blank if you are working on local server
$dbname = "myDB";//your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
register.php
<?php
include('connection.php');// added the connection here
if (isset($_POST['submit'])) {
$name = $conn->real_escape_string($_POST["name"]);
$lastName = $conn->real_escape_string($_POST["lastname"]);
$email =$conn->real_escape_string($_POST["email"]);
$location = $conn->real_escape_string($_POST["location"]);
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club (name, lastname, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
First of all define the db server connection in same php page or you may include the connection. Php file for this purpose.
Secondly it you wish to use MySQL db simple use musql_query($sql, $con) then write below lines of after inserting results.
Sorry I posted it from my mobile if you need I can post you entire code sample from my PC.

PHP not running when trying to connect to MySQL database

I'm trying to create a simple web page that will allow students to sign out for the day using just their school username.
I have written some code to take the users input from the HTML form called "Username" and connect to a database containing all the students usernames.
It will then find the student's details within the database and sign them out.
So far all the client side code works, but as soon as the PHP try's to connect to the database, everything stops running and no error codes appear apart from the occasional HTTP 500 Error depending on which part of the code I isolate?
<html>
<head>
<?php include 'head.php'; ?>
</head>
<body>
<form method="post" action="/index.php" class="login_form">
<input type="text" name="Username" placeholder="School Username">
<input type="submit" value="Sign Out">
</form>
<?php
session_start();
// These details are used for logging in
$sql_servername = "localhost";
$sql_username = "root";
$sql_password = "NotaRealPassword";
$sql_database = "student_info";
$username = $_POST['Username'];
echo "Test 1";
// Create connection
$con = mysqli_connect($sql_servername, $sql_username, $sql_password, $sql_database);
echo "Test 2";
// Check Connection
if (!$con){
die("Connection Failed: " . mysql_error());
}
echo "Connected To Database Sucessfully! ";
echo "Test 3";
//Perform Queries
$result = mysql_query(con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
echo "Test 4";
echo "Username: " . $username . "<br>";
echo "Username: " . $UN . "<br>";
echo "First Name: " . $FN . "<br>";
echo "Last Name: " . $LN . "<br>";
echo "Database Output: " . $result;
//Close Connection
mysqli_close($con);
?>
You are mixing mysqli_* and mysql_*, don't think that makes sense. Also as mentioned in the comments, this is unsafe - it puts you at risk of SQL injection. Take a look at PDO.
The query you want to execute, needs the $con variable, yet you forgot to write the $. Which means you'd get an error.
$result = mysql_query(con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
Should be, but also should not be:
$result = mysqli_query($con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
1) Your session_start() is in the wrong place.
2) You're mixing mysql_ with mysqli_ PHP functions. They are not compatible.
3) As referenced in comments you are referencing a variable but you've forgotten to add the $ , so it's actually be assumed to be a CONSTANT (which is undefined).
4) You would have found all of these things out yourself if you've used PHP Error reporting.
5) Your MySql result ($result = mysql_query(...)) is not usable, it's an SQL result and not something PHP can naturally handle.
As a worse case fix you want to be using $output = mysqli_fetch_array($result); or similar methods to turn the result into usable PHP variables. Even better if you read point 6 and employ Prepared Statements.
6) Your SQL code is unsafe and you should urgently look at using PHP Prepared Statements.
Please read suggestion 4 again, and now you've read it twice, read it a third time and checkout the link. This suggestion will save you hours of time, and will help you learn your craft, rather than asking Stack Overflow for answers.
Cheers.

Correction on Inserting data into SQL Table via PHP

I've been using php and mysql for my computing project and I've just run into this small problem. I've tried countless numbers of variations to this line of code but I always seem to receive an SQL Error.
Background Information:
HTML Document that contains a form, allowing the Admin to upload an image path, a name for the photo and a comment as well
PHP Document containing SQL that runs the code for this. I've worked out how to insert either an image path, a name or a comment but not all three at once...
Here's the line of code that causes the problem, specifically inserting the data into the database.
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[ VALUES GO HERE, WHAT SYNTAX/HOW??? ]}')";
The HTML Form is here (for anyone interested):
<form action="insertTest.php" method="POST" enctype="multipart/form-data">
Image: <input type="text" name="image" /><br>
Name: <input type="text" name="name" /><br>
Comment: <input type="text" name="comment" /><br>
<input type="submit">
</form>
PHP Doc (whole upload file, quite small, changed password for security xD):
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "admin_db";
// Create connection
$conn = new mysqli($servername = "localhost", $username = "root", $password = "password", $dbname = "admin_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[]}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image', '$name', '$comment')";
you can set variables to the associative array (with name from html form) and include each in the sql query. Something like this:
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image','$name','$comment')";
Separate your variables $imgpath=$_POST["path"]; $imgname=$_POST["name"]; $imgcomment=$_POST["comment"]; now insert into table.... INSERT INTO imgtable(path,name,comment) VALUES('$imgpath','$imgname','$imgcomment')

MySQL connection doesn't work Ubuntu?

I have installed lamp on Ubuntu and everything is working fine i tried localhost/testphp() that works fine but when I put that code it shows the values if i echo them but it doesnt insert them in the db and it doesnt give error on mysql connection either.
using POST method to send form data
<form action="form.php" method="POST">
<label>Email:</label>
<input type="text" name="name">
<label>Password</label>
<input type="password" name="pass">
</form>
and here is the php code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "hello I am here !<br/>";
$con=mysqli_connect("localhost","root","123","login");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$password = $_POST['pass'];
echo " Name: ".$name." <br/>Password: ".$password;
mysqli_query($con,"INSERT INTO login_data (username, password) VALUES ('". $name ."', '". $password ."')");
//it doesnt insert the data
//how do i check the error of that query ?
mysqli_close($con);
?>
Help !
$sql="INSERT INTO login_data(username,password) values(".$_POST['name'].",".$_POST['password'].")";
mysqli_query( mysqli $link , string $query)
First connection, then the query. And use mysqli
$a=mysqli_query($con, $sql );
First of all you can enable PHP errors with your php.ini with :
display_errors = on
Or by using a .htaccess file.
Then the sql may be :
$sql = "INSERT INTO login_data(username, password) VALUES ('". $name ."', '". $password ."')";
As Don said, you use mysqli and then mysql. You have to use mysqli_query();
your sql statement is incorrect :
$sql="Insert into login_data(username,password) values("$name","$password")";
It should be
$sql="Insert into login_data(username,password) values("'".$name."'","'".$password."'")";
since $name and $password are predefined, you just need to pass them with proper quotes.

I cant get the form data to go into database. What am I doing wrong?

CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.

Categories