What I'm trying to do is saving some data in the database and when user will press "SAVE" button script will compare the data entered by the user with data already present in the database. If the data matches it will show a warning that is "The entered data is already in the database please use search bar to search it." In my case I only want it to check phone number and cnic (cnic = national identity card number). Here is what I am doing.
<?php include_once("config.php"); // mysql_connect and database selection are in this file.
$name = $_POST['name']; // data coming from save_info.php
$gender = $_POST['option']; // data coming from save_info.php
$cnic = $_POST['cnic']; // data coming from save_info.php
$number = $_POST['number']; // data coming from save_info.php
$address = $_POST['address']; // data coming from save_info.php
$info = $_POST['info']; // data coming from save_info.php
$check = "SELECT * FROM info WHERE num = $number AND cnic = $cnic"; // checking data
$cresult = mysql_query($check);
if (mysql_num_rows($cresult)==1) {
echo "The entered phone number/cnic is already in the database, Please use search bar to search it.";
header('refresh:10;url=save_info.php');
}
else
{
$sql = "INSERT INTO info(name, gender, cnic, num, address, info)VALUES('$name', '$gender', '$cnic', '$number', '$address', '$info')";
$result = mysql_query($sql);
mysql_close();
header('Location:saved_info.php');
}
?>
You probably missed the quotes in your query:
$check = "SELECT * FROM info WHERE num = \"$number\" AND cnic = \"$cnic\"";
Since the fields are probably textual (varchar or something like that) you need to tell where the limits of the values you're comparing to are.
Also if you need to skip the saving if any of the values matches you should use OR:
$check = "SELECT * FROM info WHERE num = \"$number\" OR cnic = \"$cnic\"";
Try to add single quotes around your parameters and rewrite the query like this..
$check = "SELECT * FROM `info` WHERE `num` = '$number' OR cnic='$cnic'";
Also, on your if statement.. check like this
if (mysql_num_rows($cresult)>0) {
Also, stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
Related
// Create Your Variables
$First_Name = trim($_POST['First_Name']);
$Last_Name = trim($_POST['Last_Name']);
$Party_Size = trim($_POST['Party_Size']);
$Telephone = trim($_POST['Telephone']);
// Validate the Telephone Number before inserting into MySQL
if(!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $Telephone)) {
echo "Please go back and enter a valid Telephone number using dashes.";
// Stop the Script if the Regular Expression does not match our sequence in the Database.
exit;
}
The problem is below. When I check if the user exists in the database the script works but if you add spaces it doesn't match the existing record in the database. Any suggestions?
$check = "SELECT * FROM Weddings WHERE First_Name = '$_POST[First_Name])' AND Last_Name = '$_POST[Last_Name])'";
$results = mysqli_query($mysqli, $check);
$data = mysqli_fetch_array($results, MYSQLI_ASSOC);
if ($data > 1) {
echo "You are already in our database. Someone will contact you soon.";
exit;
}
$firstname = mysqli_real_escape_string($mysqli, $_POST['First_Name']);
$lastname = mysqli_real_escape_string($mysqli, $_POST['Last_Name']);
$check = "SELECT * FROM Weddings WHERE First_Name LIKE '%{$firstname}%' AND Last_Name LIKE '%{$lastname}%'";
$results = mysqli_query($mysqli, $check);
$data = mysqli_fetch_array($results, MYSQLI_ASSOC);
if ($data > 1) {
echo "You are already in our database. Someone will contact you soon.";
exit;
}
As you can see, I added two extra lines that were suggested by geoffrey.
mysqli_real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection.
Whenever you are allowing your users to enter some data that will be used in a query, you always should escape that data before executing the query. Not every user is a friendly user. If a user has knowledge about SQL injection attack, he can easily type some parts of SQL that will enable him to do something that you don't want.
For example, let's say user entered John as the first name and Doe as the last name. When combined with the query, it looks like this SELECT * FROM Weddings WHERE First_Name LIKE 'John' AND Last_Name LIKE 'Doe'. Nothing wrong with it.
But, what if user enters 1' OR '1' = '1 as the first name and as the last name. Then when combined with the query it will look like this SELECT * FROM Weddings WHERE First_Name LIKE '1' OR '1' = '1' AND Last_Name LIKE '1' OR '1' = '1'. Once executed, it will return all rows in your table. Learn more about SQL injection.
Just realised the other answer posted here is incorrect, it performs a like query which is not the OP's intent. The below answer trims any leading or trailing whitespace from the posted values, escapes them for security, and then performs an exact match on them. By default MySQL performs case insensitive searches and as such the case of the name will not matter.
$firstname = mysqli_real_escape_string($mysqli, trim($_POST['First_Name']));
$lastname = mysqli_real_escape_string($mysqli, trim($_POST['Last_Name']));
$check = "SELECT * FROM Weddings WHERE First_Name = '$firstname' AND Last_Name = '$lastname'";
$results = mysqli_query($mysqli, $check);
if (mysqli_num_rows($results) > 0) {
echo "You are already in our database. Someone will contact you soon.";
exit;
}
Please note that using someone's full name to check for existence is not reliable, it is better to use something that is unique such as their email address.
There are two issues with the script. The posted data is tainted until you check that you're getting from the user what you expect. At this point, the user could enter a first name of "123". So, it should be checked for being alphabetical and the surname should be checked for being alphabetical and the possibility of an apostrophe or a hyphen, so a last name like "O'Reilly" as well as "Smith-Jones" is accepted, as follows:
<?php
$fname = $lname = "";
// check for tainted data
if (ctype_alpha($_POST['First_Name'])) {
$fname = trim($_POST['First_Name']);
}
if ( preg_match("/^[a-zA-Z'-]+$/, $_POST['Last_Name']) ) {
$lname = trim($_POST['Last_Name']);
}
Once, the data validates, then it is appropriate to pass data to trim() to remove superfluous space characters, such as a blank space, tab, newline, etc.
The second issue is making sure that the query is not vulnerable to SQL injection.
<?php
if (strlen($fname) > 0 && strlen($lname) > 0) {
$firstname = mysqli_real_escape_string($link, trim($fname));
$lastname = mysqli_real_escape_string($link, trim($fname));
$query = "SELECT * FROM Weddings WHERE First_Name = '$firstname' AND Last_Name = '$lastname'";
$results = mysqli_query($link, $query or die( mysqli_error($link) ) );
if (mysqli_num_rows( $results ) > 0) {
echo "You are already in our database. Someone will contact you soon.";
exit;
}
mysqli_close($link);
}
The problem tho' has not been adequately resolved as you can still get around mysqli_real_escape_string() if you're a hacker. Per the Manual:
The character set must be set either at the server level, or with the
API function mysqli_set_charset() for it to affect
mysqli_real_escape_string().
This article offers further insight. So, it is actually better to use prepared statements., as follows:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
$stmt = $dbh->prepare("SELECT * FROM Weddings WHERE First_Name = ? AND Last_Name = ?");
if ($stmt->execute( array( $fname,$lname))) {
$row = $stmt->fetch(PDO::FETCH_ASSOC));
if ($row !== FALSE){
echo "You are already in our database. Someone will contact you soon.";
}
}
I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.
First off, I know about sql injection and that my code is not foolproof, prone to injection etc. Will be working on that next.
Now : from my Android app to my PHP file I submit a JSON array of phone numbers like :
[{"phone_number":"+12345678"},
{"phone_number":"+23456789"},
{"phone_number":"34567890"},
{"phone_number":"45678901"}
etc... etc...
These are contacts in my app user's phone. If these contacts are people who are also users of my app then I want to insert those numbers into my contacts table.
But I can't get it to work. mysqli_fetch_assoc isn't working correctly. I don't know why.
In my contacts table I have 3 columns - an auto increment, user_id and contact_id. The first two values are inserted correctly but the contact_id is always put in as '0', which is wrong.
Here is my code :
require('dbConnect.php');
//this is me, +567890123, my user_id in the user table
$user_id = '20';
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumber'];
$array = json_decode($json);
foreach ($array as $value) {
$phonenumber = $value->phone_number;
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
echo "phonenumber is " . $phonenumber . "<br>";
// we want to put $phonenumber in the contacts table, as one of +567890123 contacts
// In the user table get the associated rows of $phonenumber
while ($row = mysqli_fetch_assoc($result)) {
// get the associated user_id in that row, that's what we want to put into the contacts table
$contact_id = $row['user_id'];
$insert_into_contacts_command = "INSERT INTO contacts VALUES(NULL, '$user_id','$contact_id')";
$insert_into_contacts_table = mysqli_query($con, $insert_into_contacts_command);
}
} //if +353864677745 is NOT in the user table...
else {
echo 'not a match.';
}
}
$contact_id = $row['user_id'];
Here $contact_id will be null, because you are trying to access not existing field $row['user_id'] of the $row .
Actually there is only one field username in your results set, as you specified:
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
Try to change your query to this:
$sql = "SELECT user_id, username FROM user WHERE username = '$phonenumber'";
Your query selects the column username, not userid.
You haven't posted anything about the table user, so it's hard to suggest a new query, but I guess it's the following:
$stmt = mysqli_prepare($con, "SELECT userid FROM user WHERE username = ?");
$stmt->bind_param("s", $phonenumber);
$stmt->execute();
$stmt->bind_result($userid);
while ($stmt->fetch()) {
// Work with $userid
}
You'll note that this uses a prepared statement with a bound parameter. That way, your code is not prone to SQL injections.
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.