I created this for one of my projects. We have a webshop where users can enter their credentials and order products. The current solution puts all the data into a .csv-file and I was tasked with creating a mysql database as a new solution.
I added a simple HTML insert for the user to enter his name, but if I try to run the script I get a syntax error for line 19. I'm new to programming and therefore not sure what the error is here.
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
// create a variable
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
//Execute the query
mysqli_query($connect "INSERT INTO tbl_bestellungen(Vorname,Nachname)
VALUES('$Vorname','$Nachname')");
<?php include 'database.php';>
if(mysqli_affected_rows($connect) > 0){
echo "<p>Bestellung erfasst</p>";
} else {
echo "Bestellvorgang fehlgeschlagen<br />";
echo mysqli_error ($connect);
<h2>Text Input</h2>
<form>
Vorname:<br>
<input type="text" name="Vorname">
<br>
Nachname:<br>
<input type="text" name="Nachname">
<input type="submit" name="button1" value="Senden">
</form>
</body>
</html>
Thanks in advance.
Well you should do like this way:
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
$dbConn = mysqli_connect($servername, $username, $password, $dbname);
if(!$dbConn){
echo "No Db connected";
}
//above connection code should be in a separate file and include in all files or header
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('$Vorname','$Nachname')";
or you can set query like
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('".$Vorname."','".$Nachname."')";
if($dbConn->query($query)){
echo "Record inserted !";
}else{
echo "Record cannot be inserted !";
}
Related
Before anyone says this is a duplicate, I have checked and tried the solutions from this previously asked question. My question is different, I believe, because I don't have a separate php file - it's coded with tags in my HTML (so everything is in the same document).
Here is my PHP (database info left empty):
<?php
session_start();
$dbhost = '****';
$dbuser = '****';
$dbpass = '****';
$dbname = '****';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$email=$_POST['email'];
$query="INSERT INTO tableName(email)
VALUES('$email')";
mysqli_free_result($result);
mysqli_close($connection);
?>
Here is my Materialize/HTML form:
<form action="/thankyou.php" method="POST">
<p class="input-header">Enter Your Email:</p>
<input id="email" type="email" name= "email" class="validate" required>
<br></br>
<input class="waves-light btn indigo lighten-2" type="submit">
<br></br>
<br></br>
<br></br>
</form>
Any ideas for why it's not working? I checked my MAMP phpmyadmin database and nothing is getting added. Please let me know if you have any suggestions! Thanks!
This will help you: As you haven't added mysqli_query and because of that it wasn't adding data. Also here I am checking whether the form is submitted as you mentioned it's a single file.
<?php
// check if form is submitted
if(!empty($_POST['email'])) {
$dbhost = '****';
$dbuser = '****';
$dbpass = '****';
$dbname = '****';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// this line prevents sql injection
$email = mysqli_real_escape_string($connection, $_POST['email']);
$query="INSERT INTO tableName(email) VALUES('$email')";
// this statement runs your query and actually adds data to mysql
if (mysqli_query($connection, $query)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
}
?>
I am coding my first php app and I am basing it off a tutorial I was working on that worked. My code as of right now works fine until I get to the $var = $connection->query("INSERT INTO . . . etc.
At this point, the code immediately after the first $ just shows up as plaintext in firefox. (google shows the whole thing as text blah).
I will post my code here:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "cowboyserver";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword);
mysqli_select_db($dbName, $conn);
$email = ($_POST['email']);
if(!$conn){
echo 'error';
}else{
$query = $conn->query("INSERT INTO email_list (email) VALUES ('$email')");
}
mysqli_query($query);
header("Location: ../index.html?signup=success");
echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>' ;
Additionally, here is the HTML : : : :
<form autocomplete="on" action="includes/signup.inc.php" method="POST">
<input type="email" name="email" placeholder="put your email here" class="blah"/>
</form>
EDIT:
After trying some solutions, I have found that my php code breaks at a seemingly random point in the code. In the second answer posted, for example, the php code runs until it gets to "$conn->connect_error" in the if statement and then prints out everything after the -> instead of executing it.
Changes you needed:-
1.Need to change file name from signup.inc.php to signup.php and then use it in from like below:-
<form autocomplete="on" action="includes/signup.php" method="POST">
<input type="email" name="email" placeholder="put your email here" class="blah"/>
</form>
2.change in signup.php(the file you renamed) code (changes are commented):-
<?php
//comment these two lines when code executed successfully
error_reporting(E_ALL);
ini_set('display_errors',1);
if(!empty($_POST['email']){ // check posted data coming or not
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "cowboyserver";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword,$dbName); //add dbname here itself
//check conneced or not
if(!$conn){ // $ missed
die('connection problem'.mysqli_connect_error());//check for real connection problem
}else{
$email = $_POST['email'];// remove ()
//don't mix oop way to procedural way and use prepared statements
$stmt = mysqli_prepare($conn, "INSERT INTO email_list (email) VALUES (?)"));
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $email);
/* execute query */
if(mysqli_stmt_execute($stmt)){//check query executes or not
header("Location: ../index.html?signup=success");
echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>';
exit();
}else{
echo "insersion failde because of".mysqli_error($conn);
}
}
}else{
echo "please fill the form";
}
Note:- always use prepared statements to prevent from SQL INJECTION.Thanks
Try this. Change your form to include a submit button. Then only you can access values using $_POST.
<form autocomplete="on" action="includes/signup.php" method="POST">
<input type="email" name="email" placeholder="put your email here" class="blah"/>
<input type="submit" value="Form Submission" name="submitBtn">
</form>
Your signup.php page:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "cowboyserver";
// Create connection
$conn = new mysqli($conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName));
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submitBtn'])) { //form submission occured
$email = $_POST['email'];
$sql = "INSERT INTO email_list (email) VALUES ('$email')";
if ($conn->query($sql)) {
echo '<p>email entered !! ! ! ! ! ! !! !! ! ! ! ! !</p>';
header("Location: ../index.html?signup=success");
exit();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Form Submission Error";
}
$conn->close();
?>
Hope it's helpful.
I am trying trying to receive data by making a html form and then adding receiving data by $_GET method.Whenever I try to submit my data I get an error saying 'Your file was not found' in my chrome browser,so I tried opening my php page in chrome by typing "localhost/...." in my address bar and there it was displaying 'Database NOT Found'
here is my php code:-
<html>
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$db_handle = mysql_connect($server , $user_name, $password,"addresbook"); //adressbook is where all the tabels are
$db_found = mysql_select_db($database, $db_handle);
if (!$db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysql_query($sql,$db_handle);
}
else {
print "Database NOT Found ";
}
?>
</html>
here is mt html code:-
<form action="practic.php"method="get">
Firstname:<input type="text" name="fname"><br>
Lastname:<input type="text" name="sname"><br>
Address:<input type="text" name="address"><br>
<input type="submit">
</form>
btw i am using wamp server.Thanks in advance.
$db_found will be true on success, so your condition should be
if ($db_found) { // make DB changes etc.
and switch to MySQLi or PDO and use prepared statements as already mentioned, refer to the manual:
http://php.net/manual/en/mysqli.prepare.php
use mysqli_connect because mysql_connect is now deprecated.
$db_handle = mysqli_connect($server , $user_name, $password,$database);
refer here for connection
http://www.w3schools.com/php/func_mysqli_connect.asp
Hi change your code to use MysqLi or use PDO
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$con = mysqli_connect($server,$user_name,$password,'adresbook');//adresbook is where all the tabels are
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Change database to "adresbook"
$db_found = mysqli_select_db($con,'adresbook');
if ($db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysqli_query($con, $sql);
}
else {
print "Database NOT Found ";
}
?>
Your phpMyadmin should look like this with the database addresbook with a single s.
EDIT: I found the problem. The connection problem was located on the other page I was redirecting to, which had the wrong credentials, I'm an idiot.
This is my first time asking a quesiton in here, so bear with me.
I wanted to test to see whether or not I am able to insert data into my MySQL database through my .php page. Although I seemingly can't connect to my database, even though the username, password and so on are all correct. I use the same credentials, when I log on to the local instance trough MySQL Workbench.
The error i get in my browser says this:
Connection failed: Access denied for user 'root'#'localhost' (using password: YES)
Also this is my first time coding php, so the code is probably littered with errors, feel free to point them out.
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function prepareInput($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "praktikdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//---------------------------------------
$username1 = $password1 = "";
$errUsername = $errPassword = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["username"])){
$errUsername = "Username is required";
}
else{
$username1 = prepareInput($_POST["username"]);
}
if(empty($_POST["password"])){
$errPassword = "Password is required";
}
else{
$password1 = prepareInput($_POST["password"]);
}
$sql = "INSERT INTO users (username, password) VALUES('$username1', '$password1')";
$result = $conn->query($sql);
if(!$result) die("Something went wrong". $conn->error);
$result->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Registration</title>
</head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username">
<span class="error"> <?php echo $errUsername?></span>
<br>
Password: <input type="text" name="password">
<span class="error"> <?php echo $errPassword?></span>
<br>
<input type="submit" name="btnRegister" name="Register"/>
</form>
</body>
</html>
Your code is giving you a credentials problem (detected by your "Check connection" piece of your code), and that is derived of the users configuration in your MySQL Workbench. You need to configure the user you will use for your PHP connection to MySQL, along with the password, and the server the user connecting will be limited to (in this case is the localhost), and the privileges your user will have.
Also, and this is just for connecting to your database (for now consider that you won't execute a SQL query in your code), you can check if the connection it's ok with just your username, the password and the server name.
<?php
/* $servername, $username and $password goes here */
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die("Connection failed:" $conn->connect_error);
}
echo "Connection successful";
?>
I am new here and noob in programming.
I have created a script that can change a database column but now I want to take database login info from user's and the changed value from user's when they give all info correctly the script changed the database column info which was given by the user's.
Here is my login.html source code :
<html>
<center>
<form action="db.php" method="post">
DB Host: <input type="text" name="host"><br>
DB Username: <input type="text" name="usr"><br>
DB Password: <input type="password" name="psw"><br>
DB Name: <input type="text" name="dbname"><br><br><br>
Admin changed Username: <input type="text" name="admusr"><br>
Admin Changed Password: <input type="password" name="admpsw"><br>
<input type="submit">
</form>
</center>
</html>
and here is my db.php source code which can update database column info manually
<?php
$servername = "localhost";
$username = "admin";
$dbname = "mydb";
$password = "1234";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($conn,"$dbname");
$sql = "UPDATE admins SET user_login='admin1',user_pass='1234' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Is it possible to take value from user's and changed the database column info?
Sorry for bad english.
It's very bad idea... loads of security issues. But if you want to change it from received form values just change your query to this:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
// use them in query
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
You got more field which is user filling... I don't know your exact table structure. But if you want to use all of them just add received escaped values to your query:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
$host = $conn->real_escape_string($_POST['host']);
$dbname = $conn->real_escape_string($_POST['dbname']);
$admusr = $conn->real_escape_string($_POST['admusr']);
$admpsw = $conn->real_escape_string($_POST['admpsw']);
// use all of them in query depending on your table structure
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
Use $_POST variable to retrieve data that user entered on login.html page
like in db.php for $servername and $username use
$servername = $_POST['host'];
$username = $_POST['usr'];