check if data already exist inside mysql database
Your forgot to put AND
keyword inside SQL query. Update your query like this,
$query = "SELECT * FROM `booked` WHERE
`name` = '{$username}' AND
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
We used AND
here to match all the conditions, if all the conditions are matched only then it will return result.
There is another keyword called OR
which is also used in WHERE
clause. If OR
is applied within two conditions (WHERE column1=1 OR column2=2
) either of the condition should match to get the results.
You can also use mix of AND
and OR
.
Reference: http://dev.mysql.com/doc/refman/5.7/en/logical-operators.html
How to check if user already exists in MySQL with PHP
this code works fine for you...
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT * FROM persons WHERE Email = '$_POST[eMailTxt]'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
}
else
{
$newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
if (mysqli_query($con,$newUser))
{
echo "You are now registered<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}
Check whether the data already exists in MySQL
There were multiple issues in your code. I'll start with answering your question. $check
will never be set because your query isn't being executed. The $
is missing from $sql
. Additionally, you always need to sanitize/escape user input before using it in a query. If you do not sanitize it, then it is possible that a hacker might inject unwanted code into your query, doing things that you didn't want to be done. See the updated and optimized code below:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
if(isset($_POST['project']) && !empty($_POST['project'])){
//Importing our db connection script
require_once('dbConnect.php');
$project = strtoupper($_POST['project']);
//Security: input must be sanitized to prevent sql injection
$sanitized_project = mysqli_real_escape_string($con, $project);
$sql = 'SELECT * FROM Project WHERE project=' . $sanitized_project . ' LIMIT 1';// LIMIT 1 prevents sql from grabbing unneeded records
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
// a match was found
// no need insert
}
else{
//Creating an sql query
$sql = "INSERT INTO Project(project) VALUES ('$sanitized_project')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo('Added Successfully');
}
else{
echo('Could Not Add Project');
}
}
else{
echo('data is null');
}
//Closing the database
mysqli_close($con);
}
?>
PHP MySQL: Check if value already exists
As per documentation, mysqli::query
for successful SELECT queries returns a mysqli_result
object. To extract an object or array from it you should call one of the fetch_*
functions listed here. But you just need to check if there any record exists so it's preferrable to use $num_rows
property. So your code would look like:
$checkUserID = $db -> query("SELECT shortlink FROM test WHERE `shortlink` = $shortlink");
if ($checkUserID === false) {
die($db->error());
}
if ($checkUserID->num_rows) {
header("Location: error.php?title=hovsa");
exit(0);
}
Check if user already exist in MySql database in Node.js
Don't substitute a variable into the SQL, use a placeholder and a parameter array.
const selectUsername = conn.query("SELECT username FROM user WHERE username= ?", [username], function (err, row){
How to Check if value exists in a MySQL database
preferred way, using MySQLi extension (supported from PHP 5 onwards):
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
$mysqli->close();
deprecated and not supported in PHP 7 or newer:
$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
Related Topics
How to Determine If an Array Has Any Elements or Not
Where to Use MySQL_Real_Escape_String to Prevent SQL Injection
Http Header for Downloading Microsoft Word and Excel Files
Pdo Bind Unknown Number of Parameters
Use of Undefined Constant Stdin - Assumed 'Stdin' in C:\Wamp\Www\Study\Sayhello.PHP on Line 5
PHP File_Get_Contents() Behaves Differently to Browser
How to Subtract 24 Hour from Date Time Object in PHP
PHP $_Server['Php_Self'] to Include Query String
Google Map: Is a Lat/Lng Within a Polygon
PHP Twitter Replace Link and Hashtag with Real Link
Why Are My PHP Tags Converted to HTML Comments
How to Get Order Id in Woocommerce_Email_Headers Hook
How to JSON_Encode PHP Array But the Keys Without Quotes
Php: 'Or' Statement on Instruction Fail: How to Throw a New Exception