Check for duplicates before entering into database [duplicate] - php

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I'm trying to learn really basic PHP/SQL and I did search prior to asking but they're really complicated examples for me.
So here is a basic tutorial code that I used and edited lightly.
What can I add to the existing code to check if the username already exists so I don't create it again?
<html>
<body>
<?php
// put your code here
$servername = "localhost"; //should be same for you
$username = "user"; //same here
$password = "password"; //your localhost root password
$db = "myDB"; //your database name
$conn = new mysqli($servername, $username, $password, $db);
if($conn->connect_error){
die("Connection failed".$conn->connect_error);
}else{
echo "Connected<br>";
}
$sql="INSERT INTO login (username, password)
VALUES
('$_POST[username]','$_POST[password]')";
echo "<br><br>Inserting into db: ";
if($conn->query($sql)==TRUE){ //try executing the query
echo "Query executed<br>";
}
else{
echo "Query did not execute<br>";
}
$conn-> close(); //close the connection to database
?>
</body>
</html>

You could always set the username column in MySQL to be unique. It will reject any duplicates from there.

Related

Trouble inserting data into MySQL database via html and php form [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
How to enable PHP short tags?
(21 answers)
Closed 4 years ago.
I’m having trouble successfully INSERTing information into a database I created. I tried several different alternatives I found on the internet and I was hoping someone could help. From what I can tell I’m connecting to the database without a problem, the data is just not being submitted into it. I kept it very simple just for testing purposes to no avail. It’s probably something simple that a more experienced programmer could help out easily.
I’m running a server through A2Hosting that is running
“Server version: 10.2.18-MariaDB-cll-lve - MariaDB Server”
“Php version: 5.6.30”
Here is the code I have running(for security I’m substituted in info):
I did the “dummy checks” with data base table and field names, username and case of letters too.
config.php:
<?php
$host = "server.a2hosting.com";
$userName = "username";
$password = "password";
$dbName = "Database";
// Create database connection
$conn = mysql_connect ($host, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Html file - index.html:
<html><body> <form method="post" action="index.php"> <input type='text' name='first_name' id='first_name'> <input type='text’ name='last_name'> <input type=submit value="Submit"> </form>
</body></html>
Php file - index.php
<? include("config.php");
// has the access info for the DB, how to connect
// create a variable
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$query = "INSERT INTO Contact_Information (HOW_name, address) VALUES
('$first_name', '$last_name'); "; mysql_query($query); mysql_close();
?>
<html> <head> <meta HTTP-EQUIV="REFRESH" content="0; url=form1.php">
</head> </html>
$query = "INSERT INTO contact_inforamarion(how_name, address) VALUES('$first_name', '$last_name');";
$result = mysqli_query($conn, $query);
Query and result should be like this.

authenticate login with mysql [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
as stated in my username, desperately need help so sorry if its a duplicate post!
I'm trying to do up a login page that redirects me to my home page if authentication fails so my input will cross check with the database(mysql) then output either successful or error. but the result always show error. im pretty sure that it didnt went into my 1st if checking statement.
As shown below is my code:
<?php
$servername = "localhost";
$username = "read";
$password = "projecttest";
$dbname = "test-member";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$password1 = $_POST["password"];
$username1 = $_POST["username"];
$chkpassword = " SELECT password FROM member WHERE password = $password1 ";
$chkusername = " SELECT username FROM member WHERE username = $username1";
if ($conn->query($chkpassword) == TRUE ) {
echo "successful log in"
?>
<INPUT TYPE="hidden" NAME="redirect"
VALUE="http://localhost/IPproject_test1/home.php">
<?php
}
else if ($conn->query($chkpassword) == FALSE ) {
echo "error";
}
$conn->close();
?>
The issue is your query.
Let's assume the user enters as password asdf1234. Your query would look like this:
SELECT password FROM member WHERE password = asdf1234
That will fail because MySQL thinks asdf1234 is a column. If you escape the string, it should work.
$chkpassword = "SELECT password FROM member WHERE password = '{$password}'"
So the query looks like this:
SELECT password FROM member WHERE password = 'asdf1234'
I still wouldn't check on == TRUE tho, but on !== null

php can not execute after selected mysql db [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
here is my code, as you can see, I just wanna to connect mysql then insert a info field, but it seems not execute the next code after selected the db code, I am a newer in php, and it did not return an error, so I do not know where am I wrong..
<html>
<body>
Welcome <?php echo "show" ?><br>
Your email address is:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "mysql successed connected.";
mysql_select_db("flowers", $conn) or die("database flowers failed".mysql_error()) ;
echo "database successed";
$sql="INSERT INTO flowers (username, password)
VALUES
('$_POST[name]','$_POST[email]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn);
?>
</body>
</html>
test demo info
and here is the db info:
dn info
I use ubuntu 16.04 apache2
So the main issue here is that you are using a combination of mysql_ and mysql functions. Note that mysql has been depreciated since PHP5 and has been completely removed in PHP7 so you should be using the newer mysqli or PDO. I personally use PDO, however have kept your code with mysqli.
<?php
$servername = "localhost";
$username = "root";
$password = "56lj0721";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "mysql successed connected.";
mysqli_select_db($conn,"flowers") or die("database flowers failed".mysqli_error()) ;
echo "database successed";
$sql="INSERT INTO flowers (username, password)
VALUES
('$_POST[name]','$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysqli_close($conn);
?>
You should also really be using prepared statements to help prevent SQL Injection. You can read more here for mysqli.
It's also important to remember that you should be validating your $_POST['name'] and $_POST['email'] values as well, which I have not included.
If you want to read further about PDO, take a look here.
You have these two statements in your php code.
$conn = mysqli_connect($servername, $username, $password);
...
$conn = mysqli_connect($servername, $username, $password);
You should get rid of the second one if you must use the mysql_ interface to run your query.
You should also know, with respect, that only a fool uses the mysql_ interface in 2017. It has been deprecated for years, for reasons of cybersecurity, and is going away soon.

Prepared statements using MySQL not inserting POST values to database table

I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}

How do I check if a user already exists in an SQL database? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I am trying to test a simple user account registration page for a project for class, and I am trying to create a check that will notify the user if their email is already in the database, and therefore will not add them to it again. Here's my PHP code.
<?php
$collegeid = mysql_real_escape_string('1');
$email = mysql_real_escape_string('abc#test.com');
$password = mysql_real_escape_string(md5('test1'));
$name = mysql_real_escape_string('Test Test');
$bday = mysql_real_escape_string('1900-01-01');
$class = mysql_real_escape_string('Freshman');
//echo "<p>Test</p>";
$servername = "localhost";
$username = redacted;
$serverpassword = redacted;
$dbname = redacted;
$conn = new mysqli($servername, $username, $serverpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$checkquery = "SELECT * FROM Student WHERE Email = '$email'";
$insertquery = "INSERT INTO Student (CollegeID, Name, Birthday, Email, Classification, Password) VALUES ('$collegeid', '$name', '$bday', '$email', '$class', '$password')";
if (mysql_num_rows($conn->query($checkquery)) > 0)
{
echo "Error: Email already in use";
}
else
{
$conn->query($insertquery);
echo "Account Created.";
}
?>
However, it always tells me the account is created, regardless of whether or not that user is in the database.
You are mixing mysql and mysqli functions. You should not use mysql functions as they are deprecated and you seem to be using mysqli for almost everything except escaping your values and checking the number of found rows.
The problem is caused by your use of mysql_real_escape_string. When no mysql_* database connection is found, that returns false which is the equivalent of an empty string so you are checking for empty values in your database and everytime you don't find that, you add a new row.
To secure yourself against sql injection on mysqli, you should switch to prepared statements instead of using mysqli_real_escape_string.
Edit: It is also mysql_num_rows that is returning false in case of an error...

Categories