I made this code
<?php
mysql_connect ("localhost","root","root");
mysql_select_db ("new");
$newusername=$_POST ['newusername'];
$newpassword=$_POST ['newpassword'];
$submit=$_POST ['submit'];
if($submit) {
$newaccount= "INSERT INTO users (name,password) VALUES ("$newusername","$newpassword")";
$result=mysql_query($newaccount);
if ($result) {
print "account has been created"."<meta http-equiv="refresh" content="5;login.php">";
}
else {
echo " The account is already exist";
}
}
?>
but it says error on line 8 which is " insert into" line
There is a problem with double quotes. You can add concatenation:
$newaccount = "INSERT INTO users (name,password) VALUES ('" . $newusername . "','" . $newpassword . "')";
P.S. Don't use mysql_* functions (mysql extension is deprecated), use mysqli_* instead.
You used wrong quoting:
$newaccount= "INSERT INTO users (name,password) VALUES ('$newusername','$newpassword')";
Sorting out the quotes and using mysql_real_escape_string to sanitise the input (and prevent an easy SQL injection attack):-
<?php
mysql_connect("localhost","root","root");
mysql_select_db ("new");
$newusername = mysql_real_escape_string($_POST['newusername']);
$newpassword = mysql_real_escape_string($_POST['newpassword']);
$submit = $_POST['submit'];
if($submit)
{
$newaccount = "INSERT INTO users (name, password) VALUES ('$newusername', '$newpassword')";
$result = mysql_query($newaccount);
if ($result)
{
print "account has been created"."<meta http-equiv='refresh' content='5;login.php'>";
}
else
{
echo " The account is already exist";
}
}
?>
$newaccount= "INSERT INTO users (name,password) VALUES ("$newusername","$newpassword")";
TO
$newaccount= "INSERT INTO users (name,password) VALUES ('".$newusername."','".$newpassword."')";
OR TO
$newaccount= "INSERT INTO users (name,password) VALUES ('$newusername','$newpassword')";
<?php
mysql_connect ("localhost","root","root");
mysql_select_db ("new");
$newusername=$_POST ['newusername'];
$newpassword=$_POST ['newpassword'];
$submit=$_POST ['submit'];
if($submit) {
$newaccount= "INSERT INTO users (name,password) VALUES ('".$newusername."', '".$newpassword."')";
$result=mysql_query($newaccount);
if ($result) {
print "account has been created"."<meta http-equiv="refresh" content="5;login.php">";
}
else {
echo " The account is already exist";
}
}
?>
Related
Im using the following code and testing it using WAMP on my localhost.
It works fine and inserts the data however for some reason it creates duplicate row.
Is there are reason why it makes it appear twice?
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data(name, surname, age, username, password) values ('$name', '$surname', '$age', '$username', '$userpass')";
$result = mysqli_query($conn, $mysql_qry);
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Thank you
YES, you run the query TWICE, see comments in the code
<?php
require "conn.php";
$name =$_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$userpass = $_POST["password"];
$mysql_qry = "insert into employee_data
(name, surname, age, username, password)
values ('$name', '$surname', '$age', '$username', '$userpass')";
//ONCE HERE
$result = mysqli_query($conn, $mysql_qry);
//AND AGAIN HERE
if ($conn->query($mysql_qry) === TRUE){
echo "insert success";
}
else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
ALSO Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
Coded using prepared and bound queries
<?php
require "conn.php";
$sql = "insert into employee_data
(name, surname, age, username, password)
values (?,?,?,?,?)";
$stmt = $conn-prepare($sql);
$stmt->bind_param('sssss', $_POST["name"],
$_POST["surname"];
$_POST["username"];
$_POST["password"];
if ( $stmt->execute() ){
echo "insert success";
}else{
echo "Error:" .$mysql_qry . "<br> " . $conn->error;
}
$conn->close();
?>
Now I have to mention how bad it is to use Plain Text Password.
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.
I am creating a database for employees, and I am applying the crud operation to it
The problem with the code is that I cannot insert data into the database from the fields, I also get this error:
do not access superglobal $_post array directly.
<?php
session_start();
include("configa.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"]);
$LastName = filter_input(INPUT_POST, $_POST["LastName"]);
// attempt insert query execution
$sql = "INSERT INTO employeeinfo (FirstName, LastName) VALUES ('$FirstName', '$LastName')";
if(mysqli_query($mysqli, $sql)){
echo "Records added successfully.";}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysqli);
}
// close connection
$sql = 'INSERT INTO `employeeinfo`(`FirstName`, `LastName`) ';
$sql = $sql . "VALUES (\"$FirstName\", \"$LastName\") ";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
$_SESSION['completed'] = "YES";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
header('Location: Employee.php');
}else
{
echo 'BYE BYE !!!';
}
mysqli_close($mysqli);
?>
So the filter_input() method in php accepts a third parameter specifying what it should do as a filtering function. You could go with the filter FILTER_SANITIZE_STRING, judging by your case.
Refer the filter_array method in php manual : http://php.net/manual/en/function.filter-input.php
Refer what filters are available in php : http://php.net/manual/en/filter.filters.php
What Filter am I using for this demo : http://php.net/manual/en/filter.filters.sanitize.php
So your input assignment to variables will look like the following,
$FirstName = filter_input(INPUT_POST, $_POST["FirstName"], FILTER_SANITIZE_STRING);
$LastName = filter_input(INPUT_POST, $_POST["LastName"], FILTER_SANITIZE_STRING);
And i gather you might be using NetBeans for PHP development (https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new). This has the same warning as you've mentioned. But I'm not quite sure you will see the warning around other IDE's.
Trying to build an email list in a database. I made this code, but it's not working and i'm not getting any errors. Am I on the right track?
HTML:
<div id="signup">
<h1>Sign-Up For Our Newsletter!</h1>
<form method="post" action="scripts/php/addSubscription.php">
<label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
</form>
</div>
PHP:
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo 'Sorry, An error occured. Please try again.';
}
mysqli_close($conn);
$conn is a variable in mysqli_connect.php
Adding contents of mysqli_connect.php just for reference:
<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>
I use this on several databases and it connects each time.
EDIT:
Updated code per answers/comments and still nothing is happening.
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
SOLVED:
require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
You are currently getting an error but your code doesn't show you. Print the error for a start:
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
The real error you are getting is a syntax error. This is how your generated SQL looks like:
INSERT INTO newsletterusers (email) VALUES (hello#email.com)
Note that there are no quotes around it, you can fix it by surrounding $email with quotes:
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
I'm trying to use this code to be able to stop double bookings in my booking system. At the moment when you enter the same time twice then it comes up with this error:
Email is validthis time is already booked
Notice: Undefined variable: sql in C:\xampp\htdocs\book.php on line 44
Warning: mysqli_query(): Empty query in C:\xampp\htdocs\book.php on line 44
Error:
this is my code
<?php
//$error = ""; // Initialize error as blank
$con=mysqli_connect("localhost","","","");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = $_POST['email'];
$time = $_POST["time"];
$name = $_POST["name"];
$surname = $_POST["surname"];
$date = $_POST["date"];
$adl1 = $_POST["adl1"];
$adl2 = $_POST["adl2"];
$postcode = $_POST["postcode"];
if(!filter_var(($email), FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "Email is valid";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
if(mysqli_num_rows($result) == 0)
{
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
}
else
{
echo("this time is already booked");
}
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
}
Basically I think it's trying to access the $sql inside the if statement but I have no idea why it can't. Unless i'm being stupid.
You can rewrite your code as, since in else condition there is no query to the mysqli_query(), that why you got the error,
if(mysqli_num_rows($result) == 0){
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
} else {
echo("this time is already booked");
}
Set $sql as "global" -> you just need to create it before the if-statement.
Try to declare $sql value on top of your php code your code not execute
if(mysqli_num_rows($result) == 0)
{
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
}
this condition its actually executing your else body that why it generate exception that $sql variable not defined