So I have my form that sends data to my php file that then enters it into the database. Here's the php backend part
<?php
$db = new mysqli('localhost','root','x','app');
$username = $_POST['username'];
$db->query("INSERT INTO people (first_name) VALUES ('{$username}'");
?>
But my question is, why isn't username being put into the database?
You are missing a bracket ) in the following line:
("INSERT INTO people (first_name) VALUES ('{$username}' ")
^ // <= right there
change it to:
("INSERT INTO people (first_name) VALUES ('{$username}')")
Yet, as pointed out in comments, you are open to SQL injection when using your present method.
Use prepared statements, or PDO.
Here follows an example of a prepared statement:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = #mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$mysqli) {
die('Connect Error: ' . mysqli_connect_error());
}
// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$sql = ("INSERT INTO people (first_name) VALUES (?)");
$stmt = $mysqli->prepare($sql) or die("Failed Execution");
$stmt->bind_param('s', $username);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
Plus, using error reporting is important before going live.
http://www.php.net/mysqli_error
Should you want to get into learning PDO,
Here are a few tutorials for you to look into:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Here is a PDO example:
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try{
$db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$email = $_POST['email'];
$username = $_POST['username'];
$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`)
VALUES (:email, :username)");
$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);
$result_set->execute(array(':email' => $email, ':username' => $username));
echo "Data successfully written.";
return $db;
}catch(PDOException $e){
echo $e;
return false;
}
?>
PDO error handling links:
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
All I want is to get the var1 from the input into my SQL table. It always creates a new ID, so this is working, but it leaves an empty field in row Email. I never worked with SQL before and couldn't find something similar here. I thought the problem could also be in the settings of the table, but couldn't find anything wrong there.
<input name="var1" id="contact-email2" class="contact-input abo-email" type="text" placeholder="Email *" required="required"/>
<form class="newsletter-form" action="newsletter.php" method="POST">
<button class="contact-submit" id="abo-button" type="submit" value="Abonnieren">Absenden
</button>
</form>
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
// Connection to DBase
$con = new mysqli($host, $user, $password, $dbase) or die("Can't connect");
$var1 = $_POST['var1'];
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
$result = mysqli_query($con, $sql) or die("Not working");
echo 'You are in!' . '<br>';
mysqli_close($con);
is the id a unique id? that's auto-incremented??
if so you should do something like this
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host,$user,$password,$dbase);
$email = $_POST['var1'];
// you might want to make sure the string is safe this is escaping any special characters
$statment = $mysqli->prepare("INSERT INTO table (Email) VALUES (?)");
$statment->bind_param("s", $email);
if(isset($_POST['var1'])) {
$statment->execute();
}
$mysqli->close();
$statment->close();
Simple answer
There are a few things wrong here; but the simple answer is that:
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
...should be:
$sql = "INSERT INTO {$table} (id, Email) VALUES ('?', '{$var1}')";
...OR assuming id is set to auto-increment etc. etc.
$sql = "INSERT INTO {$table} (Email) VALUES ('{$var1}')";
More involved answer
You should really take the time to use prepared statements with SQL that has user inputs. At the very least you should escape the strings yourself before using them in a query.
mysqli
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host, $user, $password, $dbase); // Make connection to DB
if($mysqli->connect_error) {
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("s", $email); // Bind $email {s = data type string} to the ? in the SQL
$query->execute(); // Execute the query
PDO
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
try {
$pdo = new pdo( "mysql:host={$host};dbname={$dbase}", $user, $password); // Make connection to DB
}
catch(PDOexception $e){
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$email]); // Execute the query binding `(array)0=>$email` to place holder in SQL
I new with PHP, MySQL and PDO.
With a lot of search, I made this piece of code to insert a new user/customer with a password.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt -> execute();
$conn = null;
?>
<html>
<body>
Welcome <?php echo $_POST["email"]; ?><br>
Your password is: <?php echo $_POST["password"]; ?>
</body>
</html>
When I submit, go to another PHP page, say the user's email and password.
So when I do SELECT * FROM, I receive an empty SET.
(Basically, the Insert is not working, but on the PHP page, it says the information that was inserted in the INSERT)
What am I doing wrong?
Basically, what I was doing wrong was calling a statement after its values.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$stmt -> execute();
$conn = null;
?>
Please be gentle with me i have just recently trying to learn PHP/SQL.
The problem is that the first query is ALWAYS TRUE when it shouldn't (base on what i know).
The query simply state to get the 'username' where betakey=$betakey provided by user. The fact that my datebase columns is still empty except column betakey doesn't make that query statement true at all.
Please help, maybe i am missing some knowledge on this.
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host="localhost"; // Host name
$db_username="**"; // Mysql username
$db_password="**"; // Mysql password
$db_name="**"; // Database name
$conn = mysqli_connect("$host", "$db_username", "$db_password","$db_name");
if (!$conn){
die ("Error: ".mysqli_connect_error());
}
$query1 = "SELECT username='$username' FROM users2 WHERE betakey='$betakey';";
$result_1 = mysqli_query($conn,$query1);
if(mysqli_num_rows($result_1) > 0){
echo 'Beta key is used';
}else{
$query2 = "UPDATE users2 SET firstName='$firstName',lastName='$lastName',username='$username',password='$password' WHERE betakey='$betakey'";
echo 'Registration Successful';
}
mysqli_close($conn);//Close off the MySQL connection to save resources.
?>
You have plenty of problems in your code. Let me help you fix some of them
You should learn how to properly open mysqli connection. You need to enable error reporting and set the correct charset.
You should never concatenate PHP variables into SQL query. Always use parameterized prepared statements instead of manually building your queries.
Your first SQL query has an error. username='$username' is meaningless and wrong. If all you want to do is check existence use COUNT(1) or something similar.
Here is my take on your fixed code:
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host = "localhost"; // Host name
$db_username = "**"; // Mysql username
$db_password = "**"; // Mysql password
$db_name = "**"; // Database name
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $db_username, $db_password, $db_name);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("SELECT COUNT(username) FROM users2 WHERE betakey=?");
$stmt->bind_param('s', $_GET['rusername']);
$stmt->execute();
$result_1 = $stmt->get_result();
$used = $result_1->fetch_row()[0];
if ($used) {
echo 'Beta key is used';
} else {
$stmt = $conn->prepare("UPDATE users2 SET firstName=?, lastName=?, username=?, password=? WHERE betakey=?");
$stmt->bind_param('sssss', $firstName, $lastName, $username, $password, $betakey);
$stmt->execute();
echo 'Registration Successful';
}
I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php
This is my PHP code starting and used connection type is PDO.
//connection with server
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=gujaratoil", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['submit']))
{
//at the beginning null value is set
$name = $emailaddress="";
$sql = "INSERT INTO
registration(name,emailaddress)VALUES('$_POST[name]','$_POST[emailaddre
ss]')";
}
?>
I have tried all the solutions available; what should I do to solve this issue? I am using a PDO connection.
When using PDO you should use prepared statements rather than directly embedding variables in the SQL.
The reason, I believe, given the code above why the insert was failing was / is due to the lack of quotes around field names within $_POST[] ~ ie $_POST[name] which is likely to be causing undeclared constant errors
$name=$_POST['name'];
$email=$_POSt['emailaddress'];
$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
$stmt->execute();
}