PHP form doesn't insert into SQL database - php

I am trying to test a very simple PHP form that inserts input into an SQL database. The connection works fine, but the data does not appear in the database when I refresh it. I have only two files, an index.html and a process.php.
index.html:
<html>
<head>Testing</head>
<body>
<div id="frm">
<form action="process.php" method=POST>
<p>
<label>Username</label>
<input type="text" id="stuff" name="stuff">
</p>
<p>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
}
?>

The problem is that you're not actually running the query. You just assigned the query string to a variable, so it's not being executed in MySQL.
Your code is vulnerable to SQL injection, so I'm proposing a solution:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries` (`input`) VALUES (?)";
if ($stmt = $conn->prepare($sql)) { // Prepare statement
$stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
$stmt->execute(); // Run (execute) the query
$stmt->close(); //clean up
}
This code should work and also keep you secure from SQL injections.

Haven't tested it fully but I fixed your query.
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
also change the post part to: <form action="process.php" method="POST">
That should fix the problem for you
Also make sure you use the function: mysqli_real_escape_string to escape malicious user input to prevent SQL injection.
Another thing: you could change localhost to 127.0.0.1. I think this is more reliable although it's the same in most cases.

Your code is not submitting the query to the database, it is opening the connection but not submitting the query, see below to the submit query request if you use mysqli in PHP
... else {
# this submits the query
$conn -> query ($sql);
}

you need to take function mysqli_query of mysqli that will take parameter as connection object like $conn and 2nd parameter will be sql query to execute.
like this
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
to prevent from sql injection you must use PDO because PDO use paramBind to protect injection .

Related

How to ask a user input and use it as a parameter for a stored procedure in a PHP script?

Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>

php Data not stored in mySQL database using XAMPP

I have this code and I am using the latest version of XAMPP:
filename: store.html
<!DOCTYPE html>
<html>
<body>
<form action="store.php" method="post">
User input: <input type="text" name="userinput"><br>
<input type="submit">
</form>
</body>
</html>
filename: store.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$input = $_POST["userinput"];
$sql = "INSERT INTO table_1 (s_num)
VALUES ('$input')";
?>
Whatever I do, no data is added to the database. Please help. Thank you.
The problem here is that you never executed the query.
$sql = mysqli_query($conn,"INSERT INTO table_1 (s_num)
VALUES ('$input')");
if(!sql){
echo "Error: " . mysqli_error($conn);
}
else{
echo "Success";
}
Reference:
http://php.net/manual/en/mysqli.query.php
Your present code is open to SQL injection if user-input (other than yourself) ever gets involved.
Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, seeing you are running this from your own machine, make sure you are accessing as http://localhost/file.php as opposed to file:///file.php.
You are not executing your sql insertcode.
After this line:
$sql = "INSERT INTO table_1 (s_num)
VALUES ('$input')";
Add these line:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Posting data to index,php file on a server ip

i am trying to capture some data from a IOT device. The problem isto capture the data you have to feed in the ip to the device so that data is [posted to that ip address.
To process the data,i came up with this script and aptly named it index.php
<?php
$servername = "94.049.947.776";
$username = "droid";
$password = "!#nord";
$dbname = "atree";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = $_POST;
$sql = "INSERT INTO gps (data)
VALUES ('$data')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To test it out,i have this html page
<form method="post" action="972.245.119.017">
<input type="text" name="ed" value="jsonstring" />
<input type="submit" value="submit" />
</form>
However,no data is inserted to the database. What could be wrong with my script?.
$_POST is php variable in form of an Array, maybe try to :
replace :
$data = $_POST;
with :
$data = $_POST['ed']; // the value from the form
or some other value that you posted to the index.php like :
$data = $_POST['VALUE_NAME'];
consider working with PDO (http://php.net/manual/en/book.pdo.php) for the sql part
You should replace :
$data = $_POST;
by :
$data=$_POST['ed'];

How to extract desired row from Mysql database using PHP script

I have created one HTML form which takes input from user ,Now I need to search user inputed name in Mysql database and print details related to that user inputed name which is stored in Mysql database.
Below script is creating HTML form to take user input, Saved as "ProcessTracking.html".
<form action="details.php" method="get"/>
<h3 align="center"><FONT color=#CCFF66>ENTER SO NUMBER</h3>
<p align="center">
<input type="text" id="SO_Number" name="SO_Number"/>
</p>
<div style="text-align:center">
<button type="submit" value="SEARCH">
<img alt="ok" src=
"http://www.blueprintcss.org/blueprint/plugins/buttons/icons/tick.png"/>
SEARCH
</button>
</form>
Below PHP script named as "details.php"
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($result);
#printf ("SO_Number: %s \n",$row["SO_Number"])
#print_r($row);
printf ("SO_Number:");
printf($row["SO_Number"]);
printf ('--||--');
printf ("Name:");
printf($row["Name"]);
printf ('--||--');
$conn->close();
?>
Firstlly you are not using the $_GET['SO_Number'] parameter in a WHERE of SQL statement. Secondlly you are using both mysql and mysqli which are totaly diffrent and don't work together. For usage see mysqli_fetch_row() and mysqli_query(). Also use print_r($row);.
Here is the corrected code:
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print_r($row);
$conn->close();
?>
EDIT: Added code example.
You have mixed mysql and mysqli api together. Try using either one.
Note: mysql api is deprectaed as of php 5.5.0
1st Error
As saty says it is because of the syntax error you have in this line
print_r"$row";
which should be as print_r($row)
2nd Error
You're mixing mysql & mysqli
I am not sure about the table that you have.
Recommendation :
I would recommend you to turn on the error_reporting if not those errors will be in your errors_log file
Also for debugging your sql, you can first construct your sql query, run in the phpmyadmin or related tools for your query, then fire the query and make this done.
Note :
If you are using these code in online then the error_log will be in the directory where you execute this page. (But it may change according to your hosting)
If you are running in local machine the error log may locate according to the server you use...
You can find by printing the php's configuration by phpinfo and find for
error_log
May this thing will fix your issue
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
$so = $_POST['SO_Number'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM ProcessDetails WHERE SO_Number=$so");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row[SO_Number]);
$conn->close();
?>

My data is not being stored in my database

I can't seem to figure out what is wrong with my code. I am trying to get it to take the input from
<form id="contact-form" action="emails.php" method="post">
<input placeholder="Please enter your email address" name="emailz" type="email" tabindex="2" required>
<input type="submit" name="submit" id="contact-submit" value="Subscribe">
</form>
and have it saved into my database.
Here is my PHP file:
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insert = "INSERT INTO emails(addressEmail) VALUES($_POST '$emailz')";
$conn->close();
To use MySQLi in a safe way, it's best to use Prepared Statements. This will prevent your users from inserting SQL injection or, possibly by mistake, inserting characters that can cause problems to your MySQL server.
As you can see in the script below, I'm first preparing the SQL query, using a placeholder "?" for the item variable. After I'm binding the parameter(variable) to this placeholder.
Now the query is setup correctly, it's time to execute it. It's always a good habit to close anything left open once done, as it will free up memory that's no longer in use.
<?php
/* DB Info */
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
/* MySQLi Object */
$conn = new mysqli($servername, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Prepare query */
if ($stmt = $conn->prepare("INSERT INTO emails (addressEmail) VALUES (?)")){
/* Bind POST data */
$stmt->bind_param("s", $_POST['emailz']);
/* Run query */
$stmt->execute();
/* Close statement */
$stmt->close();
}
/* Close connection */
$conn->close();
?>
Here is how you do the insert -
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO `emails`(`addressEmail`) VALUES(?)");
$stmt->bind_param('s', $email);
$email = $_POST('emailz');
$stmt->execute();
First you prepare the query and leave placeholders for the item variables. The you bind each parameter(variable) and then declare them. Finally you execute the query.
First check if the user hasn't missed anything:
if (isset($_POST['emailz']) { //code here.. };
In the code here... section, store the value of emailz in a variable like this:
$emailz = $_POST['emailz'];
Of course this may be insecure for more important data like passwords. You should use the hash() function then.
For inserting the variable in DB, try this:
$query = "INSERT INTO `user` (emailz) VALUES ('$emailz')"; $result = mysql_query($query); //inserts the variable in the DB.

Categories