INSERT INTO with PHP $_POST - php

I'm new to database development, and really struggling with formatting. For the life of me, I can't seem to flush out the errors. I have a simple html form that I am passing to my php file to submit to my local host. For whatever reason, I can't seem to add $_POST in the values. I'm sure I'm missing something, maybe someone on here can help.
Thanks in advance!
<form method="post" action="demo.php">
<input type="text" id="fname">
<input type="text" id="lname">
<input type="text" id="email">
<input type="submit" value="Go!">
</form>
My demo.php is:
<html>
<body>
<?php
$servername = "localhost";
$username = "myuser";
$password = "";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
"echo $_POST['fname']",
"echo $_POST['lname']",
"echo $_POST['email']"
)';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>

First change your form..
Look at your inputs; take this one for example:
<input type="text" id="fname">
This is missing the name attribute therefore, it won't be correctly set when you submit the form; it must be like so:
<input type="text" id="fname" name="fname">
Secondly, if you want to concatenate a string, you don't use echo, echo is used for outputting text. To attach strings together in PHP you should read the manual page on string operators
Thirdly and most importantly;
Use prepare to input your data. Never pass $_POST directly into your query.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
?,
?,
?
)';
//use ->prepare in favour of ->query
if ($stmt = $conn->prepare($sql)) {
//bind your inputs
$stmt->bind_param('sss',$_POST['fname'],$_POST['lname'],$_POST['email']);
//execute the prepared query
if($stmt->execute()){
echo "New record created successfully";
}
//You had a random ';' here that I've commented out??
//;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo "</br>Stmt error: ".$stmt->error();
}

Related

Mysql configured correctly for remote connection but php code failing connection?

I went through the grueling process of figuring out how to bind the correct address in the config file and connect mysql to my remote server. Yesterday it was working with different code and now it's not connecting. I'm getting the die "connection failed: " but its not showing me the connect_error as I called for so cant even figure out the issue? Does anyone see something wrong with my code? NOTE: I know this is unsafe and I usually do prepared statements but just trying to work with connection to the db issue now.
<?php
$server = "174.---.--.187";
$username = "dylanto";
$pass = "------";
$db = "survey";
//$port = 3306;
//create connection
$conn = new mysqli($server, $username, $pass, $db);
//check connection
if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$user = $_POST['user'];
$pass = $_POST ['pass'];
$sql = "insert into login (user, pass) values ('$user','$pass')";
if ($conn->query($sql)==TRUE) {
echo "Account created";}
else {echo "something went wrong";}
$con->close;
?>
Html code:
<html><head><title>Log-in</title>
<link rel="stylesheet" type="text/css" href="sytle.css"></head>
<body>
<center><u><strong><h2>Login</h2></u></strong></center>
<br />
<center>
<form action="signup_process.php" method="POST">
Pick Username: <br>
<input type ="text" name = "user"><br>
Pick Password:<br>
<input type ="password" name ="pass"><br>
<input type="submit" name="submit" value="Sign-up">
</form></center>
</body>
</html>
From
if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
To:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Since if ($conn->connect_error) = If any error and if (!$conn->connect_error) if no error.
For prepared statement :
From:
$sql = "insert into login (user, pass) values ('$user','$pass')";
if ($conn->query($sql)==TRUE) {
echo "Account created";}
else {echo "something went wrong";}
To :
//sanityze POST
$user = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['user'], ENT_QUOTES, 'UTF-8')));
$pass = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['pass'], ENT_QUOTES, 'UTF-8')));
//use prepared
$stmt = $conn->prepare("insert into login (user, pass) values (?,?)");
//bind parameter
$stmt->bind_param("ss", $user, $pass)
$stmt->execute();
//then check

Store the data in mysql

i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.
There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";
Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";
1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>

PHP fails to post to MySQL Database

I have a formText.php file that contains a form with the following code form code:
<form action="insert.php" method="post">
<p>
<label for="theNames">Name:</label>
<input type="text" name="theName" id="theName">
</p>
<p>
<label for="theCitys">City:</label>
<input type="text" name="theCity" id="theCity">
</p>
<p>
<label for="theAges">Are you over eighteen?(Y/N)</label>
<input type="text" name="theAge" id="theAge">
</p>
<p>
<label for="theDates">Date:</label>
<input type="text" name="theDate" id="theDate">
</p>
<input type="submit" value="Submit">
</form>
Then I have an insert.php file with the following script:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root","phpteste");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security (EDITED)
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
// attempt insert query execution
$sql = "INSERT INTO tabelateste (id, name, city, overeighteen, date) VALUES (NULL, '$theName', '$theCity', '$theAge', '$theDate')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
My database is called phpteste and my table name is tabelateste.
What am I doing wrong here?
Whenever I click Submit nothing comes up and nothing gets added to the database.
Your post data name fields are wrong. SO you need to change below line:
// Escape user inputs for security
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
You need to change date to signup_date as per your database table structure.
$sql = "INSERT INTO tabelateste (name, city, overeighteen, signup_date) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
$sql = "INSERT INTO tabelateste (`name`, `city`, `overeighteen`, `date`) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
Use this code
I just tested your code (copied and pasted) and it works perfectly under my server configuration (Windows 10 - PHP 5.6) . My best guess is that you have a typo in either the table name or the MySQL configuration.
If you copied this code from another site. Please check that you created the database and the table , and that the MySQL configuration is correct.
A good to check for this kind of mistakes so is to read the PHP error logs
Try it like this maybe
if(isset($_POST['submit']) && !empty($_POST) ){
$theName = $_POST['theName'];
$theCity = $_POST['theCity'];
$theAge = $_POST['theAge'];
$theDate = $_POST['theDate'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "phpteste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tabelateste (name, city, overeighteen, date)
VALUES ('$theName ', '$theCity ', '$theAge ', '$theDate ')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.

Error messages when inserting data from form into sql

I have a small problem here...
I need to insert data into a database from a form. This works, but i have two problems.
When i launch the website, a blank row is added into the database.
when i launch the website and the whole time, i get a errormessage for each object i want to insert to the database. The errorcode i get is;
Notice: Undefined variable: start in C:\wamp\www\index.php on line 51
Notice: Undefined variable: start in C:\wamp\www\index.php on line 52
Notice: Undefined variable: start in C:\wamp\www\index.php on line 53
How can i fix this problem?
here is my code:
<html>
<head>
<title>ARbeidstimer</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Arbeidstimer</h2>
<div id ="register">
<form action="index.php" method="post">
<p>
<label>Start: </label>
<input type="text" name="start" class="field">
</p>
<p>
<label>Slutt:</label>
<input type="text" name="slutt" class="field">
</p>
<p>
<label for="telefon">Timer:</label>
<input type="text" name="timer" class="field">
</p>
<p>
<input type="submit" name="submit" value="send">
</p>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "timer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
}
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>
You check your submit status with if, but you dont wrap the code around if brackets, which means, the insertion and connection is still made, even though there is no submission.
Correct code:
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
ID (if its auto increment) doesn't need to be in your INSERT INTO query.
Your if condition is checking the submit is set or not but executing the query since closing braces of if is closed before the query. So just move the closing braces of if block at the end.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

Categories