How can I check if a value already exists in mySQL database? - php

I want to store a name in the mySQL database. When I click the submit button, PHP should check if the name already exists in the database. If yes then do not submit and print an error message:
Name already exists in database.
<?php
if ( !empty($_POST)) {
$name = $_POST['name'];
$valid = true;
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO people (name) values(?) ";
$q = $pdo->prepare($sql);
$q->execute(array($name));
}
}
?>
<form action="form.php" method="post">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<button type="submit" >Submit</button>
</form>

Try following query to check if a value already exists in mySQL database?
$q = $pdo->prepare("SELECT name FROM people WHERE name = :name LIMIT 1");
$q->bindValue(':name', '$name');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row = $check['name'];
// Do Something If name Already Exist
} else {
// Do Something If name Doesn't Exist
}

you could declare the column as unique and check if the query executes or not, for example:
$query = $pdo->prepare("SELECT name FROM table WHERE name = :name");
$query->bindValue(':name', '$name');
if ($query->execute()){
//no duplicate
}
else {
//error, check the error code.
echo "$stmt->errorCode()";
}
$query-> execute will retun true on success and false other wise, and the database will return an error when the input is a duplicate in a unique coulmn.
I think Making the duplication check in the database is safer.

Related

update specific field data on sql database

so i have a table of data in web ui
as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql
if($mail->Send())
{
$query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'";
$update = $con->prepare($query);
$update->execute();
}
how can i get the "update" only the data that I click on the button??
Get specific field
In order to get the specific field from a MYSQL database
Select column FROM databse WHERE x = y
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'
The issue
It's best to get a unique identifier, which no other user has used. For example a 10 digit user id code. Check that this code doesn't exist, for it to be unique.
UPDATE:
Easily use the UNIQUE SQL tag to resolve this issue.
CREATE TABLE X (
ID INT UNIQUE
)
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE id=ryan9273__2
Update a specific field
Now that we have fixed the issue we can easily
UPDATE x SET y=z WHERE id=b
Lets fix your code:
UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'
Lets make it more dynamic
UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id
final code:
$query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$update->execute();
Security Matters
You are using PDO, so use bindParam aswell. Secret code enthusiast answer isn't as secure as the current code i provided!
Practice Makes Perfect
Please don't copy my code right away. learn from it and code it again ! Make it better. Also check the official PHP documentation for more info on these topics
Stay safe !
Regards,
Ryan
you need to determine which record need to be changed based on their unique ID. usually it's the primary key of the table. so, If your primary key is enroller_id, then pass the value of enroller_id, and put it inside your sql.
if($mail->Send())
{
//prepare your query
$statement = $this->mysqli->prepare("UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE enroller_id = ?");
//check for statement preparation
if ($statement === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
//bind the value
$statement->bindParam("i", $id);
//get id for the query
$id = your_field_enroller_id;
//execute the statement
$statement->execute();
}
where enroller_id is your table primary key, and $id is the value of that field primary key.
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error)
{
die("connection failed:".$conn->connect_error);
}
$sql="UPDATE student set NAME='JohnRambo' where STUDENT_ID=1000";
$result=$conn->query($sql);
if ($result===TRUE)
{
echo"NEW RECORD CREATED SUCCESSFULLY";
}
else
{
echo "ERROR:".$sql."<br>".$conn->error;
}
$conn->close();
?>

MySql PHP PDO get single row and split to seperate values?

So how do I get single values in each seperate $stmt->bindColumn(3, $username);? What I am trying to do is set values in text fields in a form: name, username, and so on.
I pull the sandbox data from a table with:
SELECT * FROM users WHERE namn = 'sven' AND lösenord = ' ' ORDER BY datetime LIMIT 1
try {
$sql = "SELECT namn FROM user_view";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->execute();
$results=$stmt->fetchAll();
$stmt->bindColumn(1, $email);
$stmt->bindColumn(2, $name);
$stmt->bindColumn(3, $username);
$stmt->bindColumn(4, $password);
}
catch(PDOException $e) {
echo ($e->getMessage());
}
<input id="text" name="text" value="<?php echo $username ?>" type="text" class="form-control">
Assuming that your table structure is something like...
user_view
> id
> name
> email
> username
> password
And that you want to loop though all users (as you don't have a WHERE clause)...
$pdo = $dbh->getInstance(); // Get PDO instance
$sql = "
SELECT *
FROM user_view
WHERE name = ?
";
$query = $pdo->prepare($sql); // Prepare query
$query->execute([$_POST["name"]]); // Execute query and bind value to place holder (I've assumed it's coming from POST user input)
// Loop through result set
$user = $stmt->fetchObject();
// Access the columns like
# echo $user->name;
# echo $user->email;
# echo $user->username;
# echo $user->password;
// For example
echo "<input id='user_name' name='user_name' value='{$user->name}' type='text' class='form-control'>";
N.B.
You shouldn't be storing passwords in plain text - it's a major security risk.
You can use the following to hash a password on registration...
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
And to verify...
if( password_verify($_POST["password"], $db_password) ){
// Success, do something...
}

INSERT IGNORE, LIMIT 1... how to check if row exists before INSERT, to make sure it's inserted only once [duplicate]

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result:
email no longer exists publisher#example.com
This is the code I'm currently using:
if (count($_POST)) {
$email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($dbl, $query);
if (is_resource($result) && mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
} else {
echo "email no longer exists" . $email . "\n";
}
}
Is there a better way to check if a row exists in MySQL database (in my case, check if an email exists in MySQL)?
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query)) which should have simply read as if (!$query).
I apologize for overlooking that mistake.
Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_ with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
Prepared statements are best to be used to help protect against an SQL injection.
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
FYI: Forms default to a GET method if not explicity instructed.
Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.
POST arrays are case-sensitive.
Consult:
http://php.net/manual/en/tutorial.forms.php
Error checking references:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/pdo.error-handling.php
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).
You must use the same one from connecting to querying.
Consult the following about this:
Can I mix MySQL APIs in PHP?
If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:
MySql php: check if Row exists
The mysql_* functions are deprecated and will be removed from future PHP releases.
It's time to step into the 21st century.
You can also add a UNIQUE constraint to (a) row(s).
References:
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
How to check if a value already exists to avoid duplicates?
How add unique key to existing table (with non uniques rows)
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = #Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.
PDO
PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
For more examples see: How to check if email exists in the database?
MySQLi
As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]
For more examples see: How to check whether a value exists in a database using mysqli prepared statements
Minor remarks
If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record

By using php mysql create the table and retrieve the data,How to modify the data displayed in html?

I am new to the html and php, I had created the database in mysql by using the html and php,i had inserted values and retrieve the data from mysql to php,how can i modify the table means deleting the row,updating the row.
Below is my html code:
<html>
<head>
<title>STUDENT_DATA</title>
</head>
<body>
<form action="1.php" method="post" >
<center>
sname: <input type="text" name="sname" required><br></br>
sno:<input type="text" name="sno"><br></br>
marks:<input type="text" name="marks"><br></br>
class:<input type="text" name="class"><br></br>
phno:<input type="text" name="phno" onkeypress='return event.charCode >
= 48 && event.charCode <= 57'><br></br>
DOB:<input type="date" placeholder="DD-MM-YYYY"
required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
name="DOB"/><br></br>
<button>submit</button></br>
</center>
</form>
Below is my PHP code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$sname=$_POST['sname'];
$sno=$_POST['sno'];
$marks=$_POST['marks'];
$class=$_POST['class'];
$phno=$_POST['phno'];
$DOB=$_POST['DOB'];
if($sname!='' and $sno!='' and $marks!='')
{
$query = mysql_query("insert into hello1(sname, sno, marks, class, phno ,
DOB)
values ('$sname', '$sno', '$marks', '$class','$phno','$DOB')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else
{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
mysql_close($connection);
?>
Is there any one to help me?
Updation;
$query = "UPDATE hello1 SET column_name_1=value_1,column_2=value_2,... WHERE some_column=some_value;
$query = mysql_query($query);
Deletion
$query = "DELETE FROM hello1 WHERE some_column=some_value;
$query = mysql_query($query);
This is for ur comment :
take data from ur form, keep a unique constraint to use in where condition,
for example if the data u need to modify is "password" for username='admin', what u have to do is,
$query = "UPDATE hello1 SET password=$new_pw WHERE username=admin;
here $new_pasword should contain ur new pasword and username should be unique (if not, it will update all the rows with username as 'admin')
This is with reference to the code which u have sent to me.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
You cannot update like this because you haven't specified the required row(s) for updation.
for that what u have to do is just add a where condition.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
This means, u are updating name, adress and rollnumber of ur table venu, WHERE 'id' of
your row = 'the required one'
Hope this helps :)

Need assistance with a php mysql UPDATE statement tutorial please

Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";

Categories