This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
<?php
session_start();
$host="localhost";
$username="root";
$password="";
$db_name="registrering";
$tbl_name="users";
$conn = mysqli_connect($host, $username, $password, $db_name);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<html>
<head>
<title>user registration system using php and PHP and Mysq</title>
<!---<link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<div style="float:right; width:70%">
<table width="150px" border="0" cellpadding="3" cellspacing="1">
<h2>Registrer<h2/>
<form method="post" action=" ">
<br>
<tr>
<td>Brugernavn</td>
<td>:</td>
<td><input type="text" name="Brugernavn"> </td>
</tr>
<br>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" name="Email"> </td>
</tr>
<br>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="Password"></td>
</tr>
<input type="submit" name="registrer" value="Registrer">
<p>
Allerede medlem? Log ind
</p>
</form>
</div>
</table>
</body>
</html>
<?php
if (isset($_POST["registrer"]))
{
$my_username=$_POST["Brugernavn"];
$my_email=$_POST["Email"];
$my_password=$_POST["Password"];
$sql = "INSERT INTO 'users'(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
$resultat = mysqli_query($conn, $sql);
}
?>
It needs to connect to a database, but it doesn't. It's on a localhost and we can't insert data into a database. The database consists of a username, email and password.
We are using varchar(65) and utf8_general_ci.
Assuming the connection is working - the insert should have back ticks around the user name, not normal quotes.
$sql = "INSERT INTO `users`(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
I would also recommend looking into prepared statements and bind parameters, not forgetting to NOT store passwords as plane text.
Just a tip. Try using die() to print out the mysql error every time you run a mysql query. Hope it will save you a lot of effort and time in the debugging process. Also use back-ticks users near insert statement.
Related
Im trying to add a new user name to mysql table throw wordpress. But everytime I try to do it, I have no error message, but there are no lines added to the data base.
This is the wordpress page with the php inside:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
$sql="INSERT INTO `Users` (`sName`, `sEmail`)
VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
?>
I can't see whats wrong. I think it may be something wrong with the connection. Any ideas?
Thank you!
Edit
As suggested, Im trying to use $wpdb so I've created a php file in a folder call my-codes (at the same level of wp-admin, wp-content and wp-includes) and I added the following code to a file call insertUser.php:
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"sName" => $sName,
"sEmail" => $sEmail));
?>
Now in my page Im trying to call this function and Im doing this:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
if(isset($_POST['Submit']))
{
include("./my-codes/insertUsers.php");
}
?>
And im still not being able to insert any row in the database. Any suggestions?
EDIT
I needed a pluggin to actually connect my sql database with wordpress. The code is correct.
Replace your code with the code that i have provided.
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root"); // ensure that your password in empty or root in your localhost
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
if(isset($_POST['Submit']))
{
// Previous Insert Query which has discrepency in form input names and Insert Values
//$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
// My new Query with corrected form input names for Input Values during POST.
$sql = "INSERT INTO `Users`(`sName`, `sEmail`) VALUES ('".$_POST['Name']."','".$_POST['Email']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
}
Finally have a check at the table field Names and my code works fine hope it will serve you to.
use the query like this one to make thing happen,
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('".$_POST['sName']."','".$_POST['sEmail']."')";
for preventing from injection you can use this way to build query.
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('$name','$email')";
using prepared statement
$mysqli = new mysqli("example.com", "user", "password", "database");
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$stmt=$mysqli->prepare("INSERT INTO `Users` (`sName`, `sEmail`) VALUES (?,?)");
$stmt->bind_param("ss", $name,$email);
$stmt->execute();
for detailed on prepared statement got to http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
So I made this registration form but it won't send the data to my database, it works sometimes and sometimes it doesn't, it is really weird. here is the code.
<?php
error_reporting(E_ALL);
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db('Users', $con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$firstname = $_POST['firstname'];
$efternamn = $_POST['efternamn'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES ('$firstname','$efternamn','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATIOfafa";
}
}
function SignUp()
{
if (!empty($_POST['email'])) {
$query = mysql_query("SELECT * FROM Websiteusers WHERE email = '$_POST[email]' ") or die(mysql_error());
if (!$row = mysql_fetch_array($query) or die(mysql_error())) {
NewUser();
} else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if (isset($_POST['submit'])) {
SignUp();
}
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td>
</tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
What am I doing wrong here?
Update
So everytime I empty my table I am able to register again. but I can only register 1 time
Your code has so many problems, I just re-created it for you using best practices. Where you went wrong was the following:
1.Using MySQL (A depreciated class)
2.Vulnerable to SQL injection
3.You don't need functions, it's just as clean if you don't have them. You're only calling the code once.
4.Inserting $_POST[email] is not a good idea and probably won't work.
5.Fixed multiple other problems such as tags
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //Use MySQLi as MySQL is depreciated.
if (isset($_POST['submit'])) {
//No need for functions, do it all here as otherwise you'll have to declare globals.
if (!empty($_POST['email'])) {
$query = mysqli_prepare($con, "SELECT * FROM Websiteusers WHERE email = ?"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "s", $_POST['email']); //Bind the email to the SQL query
mysqli_stmt_execute($query); //Execute the query
mysqli_stmt_store_result($query); //Store the results
if(mysqli_stmt_num_rows($query) != 0) //Is the number of rows 0?
{
//rows
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
else
{
//No Rows
$query = mysqli_prepare($con, "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES (?, ?, ?, ?)"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "ssss", $_POST['firstname'], $_POST['efternamn'], $_POST['email'], $_POST['password']); //Bind the params to the SQL query
mysqli_stmt_execute($query); //Execute the query
echo "YOUR REGISTRATIOfafa";
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td> </tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
i would simplify your code and remove conditions. Shorter code will make it easier to debug and then check line by line what's happening.
A blank screen is weird unless it's something to do with the way you've set up error handling? Do u get any other warnings of something basic goes wrong? To test maybe you should try writing a line of code that definitely gets an error such as including a file that doesn't exist? Do you then get an error ? If not, it's something to do with the way you've configured your error reporting ... This doesn't solve the problem, but will bring you a step closer as when u actually get the error displayed you'll find out why the DB is not registering your form data.
What I would like to happen is for a user to fill out a form and that information be sent to a database. I am using html and php in dreamweaver, and WAM with phpMyAdmin.
I have tried everything and I cannot seem to get my .php file to work with my localhost test server (or any server for that matter). It is a sign up registration form, and there is a html document and a php document, I will include both:
HTML Form:
<table width="15px" border="0">
<form form action="localhost.php" method="POST">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Skype Name</td>
<td><input type="text" name="skype" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" /></td>
</tr>
<tr>
<td>Retype Password</td>
<td><input type="password" name="repass" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"/></td>
</tr>
</form>
PHP File:
<?php
$hostname= "localhost";
$database = "boost";
$username = "root";
$password = "";
$localhost = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno())
{
die('Connection Failed'.mysqli_error());
}
?>
<html>
<head>
<title>Sign Up</title>
</head>
<body>
<?php
if(isset($_POST['Submit']))
{
$username=$_Post['username'];
$skype=$_Post['skype'];
$email=$_Post['email'];
$pass=$_Post['pass'];
$repass=$_Post['repass'];
if(empty($username) || empty($skype) || empty($email) || empty($pass) || empty($repass))
{
echo "Cannot leave any field blank";
}
elseif ($pass!=$repass)
{
echo "Passwords did not match! Please try again.";
}
else
{
$sql="INSERT INTO users(Username,SkypeID,Email,Password) " .
"VALUES ('$username','$skype','$email','$pass')";
$res=mysqli_query($localhost,$sql);
if(!$res)
{
die("Query Failed" .mysqli_error($localhost));
}
else
{
echo "Welcome";
}
}
}
When I enter data into the fields to test it out, data is not sent to the localhost server (or the one connected to WAM). I don't know what I am doing wrong here. Are my HTML and PHP documents not interconnected to share values? Is there something wrong with the code? Am I not defining my database properly?
SOLUTION: My "POST" and "submit" where not being treated as case-sensitive. Thanks for the help.
Have you try to edit your php :
isset($_POST['Submit']
and change it to :
isset($_POST['submit']
variable $_POST is case-sensitive so you should use the exact same name that you assign in your html code.
CMIIW
I am trying to create a simple login program but the data is not going to phpMyAdmin.
I am using wamp server for phpmyadmin & have database named 'firstdatabase' and table named 'reg'.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<h1 align="center">Registration</h1>
<form action="" method="get">
<table width="261" border="1" align="center">
<tr>
<td width="85">ID : </td>
<td width="160"><label>
<input name="id" type="text" id="id" />
</label></td>
</tr>
<tr>
<td>Password :</td>
<td><label>
<input name="pass" type="password" id="pass" />
</label></td>
</tr>
<tr>
<td>Email ID : </td>
<td><label>
<input name="email" type="text" id="email" />
</label></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" name="Submit" value="Submit" />
</div></td>
</tr>
</table>
<label></label>
</form>
</body>
</html>
<?php
if ( $_POST )
{
$con=mysqli_connect('localhost','root','','firstdatabase');
if (!$con)
{
echo"Connected to server...";
}
$id=$_POST['user_id'];
$pass=$_POST['user_name'];
$email=$_POST['user_email'];
$query = "
INSERT INTO `firstdatabase`.`reg` (`user_id`, `user_pass`, 'user_email') VALUES ('$id', '$pass', '$email')";
mysql_query($query);
echo "<h2>Thank you for your registering!</h2>";
mysql_close($con);
}
?>
You are fetching the wrong fields, the ones you are fetching don't exist:
$id=$_POST['id'];
$pass=$_POST['pass'];
$email=$_POST['email'];
And you are connecting with mysqli and then are trying to run a mysql query, this won't work either.
Change this line:
mysql_query($query);
to
mysqli_query($con,$query);
Your insert query contains an error, too:
INSERT INTO `firstdatabase`.`reg` (`user_id`, `user_pass`, 'user_email') // < 'user_email'
should be
INSERT INTO `firstdatabase`.`reg` (`user_id`, `user_pass`, `user_email`) // backticks
As a sidenote, as it doesn't interrupt your program but still is wrong
$con=mysqli_connect('localhost','root','','firstdatabase');
if (!$con)
{
echo"Connected to server...";
}
Doesn't make sense. The ! in front of your $con variable will check for is not
SIDENOTE 2:
enable error reporting, all the errors you are asking for will then be displayed:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
and enable error reporting for your query!
I'm learning to put values into my db from php.
this is my simple form i wrote to test (its in a table)
<form action="connect2db.php" method="post">
<table width="500" border="0">
<tr>
<td width="200">first name:</td>
<td><input type="text" width="258" name="fname" id="fname"/></td>
</tr>
<tr>
<td width="200">last name:</td>
<td><input type="text" width="258" name="lname" id="lname"/></td>
</tr>
<tr>
<td>
your email address:
</td>
<td>
<input type="text" width="258" name="email" id="email"/>
</td>
</tr>
<tr>
<td width="200">Your message:</td>
<td><textarea rows="5" cols="45" name="mssg" id="mssg" ></textarea></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
everything works as far as page 1 sending the values to page 2, and echoing them out. but
when its time to insert them into the db table. its not working.
this is the php code:
when i do a SELECT * FROM myTableNameHere, it says "empty set", when i enter the values manually via terminal to test, i get the values fine.
here is my simple code:
<?php
$connection = mysql_connect("127.0.0.1","root","passhere");
if(!$connection) {
die("database connection failed you fool!: FIX IT!" . mysql_error()); }
$db_select = mysql_select_db("storeemail",$connection);
if(!$db_select){
die("database selection failed." . mysql_error()); }
else{ echo "connection made ";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$to = 'email#gmail.com';
$subject = 'test from my email php script';
$email = $_POST['email'];
$name = $_POST['fname'];
$lastname = $_POST['lname'];
$mssg = $_POST['mssg'];
$insertData = mysql_query("INSERT into myusers(firstname, lastname)
VALUES ('$name', '$lastname', '$email', '$mssg');");
mysql_close($connection)
?><br/>
your first name is - <?php echo $name; ?><br/>
your last name is - <?php echo $lastname ; ?><br/>
your message to send is - <?php echo $mssg; ?> <br/>
</body>
</html>
$insertData = mysql_query("INSERT into myusers(firstname, lastname)
VALUES ('$name', '$lastname', '$email', '$mssg');");
above you have specified 2 columns and giving values for four variables
myusers(firstname, lastname) gets interpreted as function. Separate myusers from paranthesis.
myusers (firstname, lastname) You also need to specify two more columns since you insert four values. And omit the trailing semi-colon withing the query string.
$insertData = mysql_query("INSERT into myusers (firstname, lastname, email, mssg) VALUES ('$name', '$lastname', '$email', '$mssg')");
Your code is also vulnerable to SQL Injections. Put you $_POST call within a mysql_real_escape_string() function call.
$email = mysql_real_escape_string($_POST['email']);
for what i can see, you are only specifying 2 columns for the insert (firstname, lastname) and 4 values (name, lastname, email, msg), so the column count does not match (either insert 2 or 4 values, and specify all of them accordingly).
after the insert, issue a mysql_error($connection) to see any errors that may arise with your queries
Here is a good article on this matter to prevent further similar questions. It covers all basic operations with MySQL tables with PHP. Isn't it's easier to ask such questions on Google first?