Checking for an empty field with MySQL - php

I've wrote a query to check for users with certain criteria, one being they have an email address.
Our site will allow a user to have or not have an email address.
$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email`!=""
');
Is this the best way to check for an empty field in SQL? I've just tried "IS NOT NULL" and this still returned a users record without them having an email address.
The query above works but out of curiosity I wondered if I'm doing it the correct way.

An empty field can be either an empty string or a NULL.
To handle both, use:
email > ''
which can benefit from the range access if you have lots of empty email record (both types) in your table.

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.
You can add the null check also
AND (email != "" OR email IS NOT NULL)

You could use
IFNULL(email, '') > ''

There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.
$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email` != "" AND `email` IS NOT NULL
');

If you want to find all records that are not NULL, and either empty or have any number of spaces, this will work:
LIKE '%\ '
Make sure that there's a space after the backslash. More info here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

check this code for the problem:
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>";
}
}
}

Related

How to make form with many query PHP MYSQL

How to make FORM with many query from input in php and mysql, should i only use query or use many condition to make the final query, here's the example of the form:
maybe like this
SELECT * FROM aset WHERE lokasi= .. OR jenis=.. OR merk=.. OR tanggal=..
how to skip the one of the WHERE clause if the input in FORM is NULL?
Thankyou!
you can check if the field is given/has any value first and then add it to the query, so you can pass the query with only provided fields using the append "=." operator to add.
$query = "SELECT * FROM aset";
if($_POST['lokasi'] != ''}{
$query =. "WHERE lokasi ='something'";
}
if($_POST['jenis'] != ''}{
if (strpos($query, "lokasi") !== false) //if lokasi exists in the query then add AND
{
$query =. " AND WHERE jenis ='something'";
} else {
$query =. " WHERE jenis ='something'";
}
}
You should or simply set your table column to DEFAULT NULL wherein everytime you insert record to the table, if there's a skip field in the form, it will still insert the query to the table.
For example when you create a table.
create table sample(id int(11) not null auto_increment,sample_column_1 varchar(255) default null,sample_column_2 varchar(255) default null,primary key(id));

How to do Multiple Condition in SQL query using PHP and Ajax

I have databse in MySQL with 21 fields which are listed below
Field Name Data Type NULL
status text No
roll_no text No
branch_id int(5) No
student_name text No
father_name text No
phone1 text No
phone2 text No
email text No
dob date No
city text No
course_id varchar(5) No
class_id int(2) No
program text No
duration text No
comment text No
admission_year int(4) No
admission_date text No
entryby text No
address text No
admission_no int(4) No
fees int(6) No
Now I am stuck with search process, I bit confused, how can I perform search for different types of conditions/criteria
Few Examples of combinations of conditions
Only those records of city=3
Only those branch_id=2
Only those admission_year='2013'
Only those course_id='15'
Only those branch_id='2' AND course_id='15'
Only those branch_id='2' AND course_id='15' AND city LIKE 'XYZ'
Only those admission_year='2012' AND course_id='10' AND duration BETWEEN(2 AND 3)
Only those branch_id=2 AND course_id='15' AND student_name LIKE 'XYZ'
Only those course_id=7 AND class_id=2 AND father_name LIKE 'XYZ'
My search.php form page is designed, I uploaded the image of form design here but I am confused how can I implement this search options for different situations.
Please give me some guidance and show me the correct way to solve this issue.
That's just plain SQL :
SELECT * FROM mytable WHERE city="3" AND branch_id=2 AND admission_year=2013 ...
Note that all fields of type int must not have quotes ( " " ) around them.
This is simple. You can do like below:
$search = "";
if(isset($records_of_city) && $records_of_city != "")
$search .= "records_of_city = 3 AND";
if(isset($branch_id) && $branch_id != "")
$search .= "branch_id = 3 AND";
if(isset($admission_year) && $admission_year != "")
$search .= "admission_year = 3 AND";
// Continue till all search criteria are appended to $search
// And at the end
$query = "SELECT * from tableName where $serach active_status = 'active'"
In query only those criteria will get appended who having some values otherwise will be ignored. One more thing is we are adding AND operator after each IF condition so you need to add one condition at the end of query (You can set condition user status, delete status etc ) so that query will not gives any error.

what is the wrong with this query?

I have a problem with this query and hope someone will help me to fix this. I am trying to check username and email address are available to register when registering a new user to my site. username is coming from login table and email address is coming from contact table. Now I need to make a query to check given username and email by new users are available to register. If those are not available I want to print error messages. I am trying to make this query something like this but its not working as I expect.
$q = "SELECT username, email FROM login
INNER JOIN contact
WHERE login.username = '$username' OR contact.email = '$email'";
Then I am checking this query in PHP like this
$r = mysqli_query ($dbc, $q);
// Get the number of rows returned:
$rows = mysqli_num_rows($r);
if ($rows == 0) { // No problems!
// register new user
} else { // The email address or username is not available.
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
} else { // One or both may be taken.
// Get row:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
if( ($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])) { // Both match.
$reg_errors['email'] = 'This email address has already been registered.3';
$reg_errors['username'] = 'This username has already been registered with this email address.4';
} elseif ($row[0] == $_POST['email']) { // Email match.
$reg_errors['email'] = 'This email address has already been registered.5';
} elseif ($row[1] == $_POST['username']) { // Username match.
$reg_errors['username'] = 'This username has already been registered.6';
}
} // End of $rows == 2 ELSE.
my problem is PHP script always going to this code. query not checking individually username and email. I trying something like this.. username not available and email available, email not available and username available. But always going to this
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
}
EDIT: Table structure..
# --------------
# Login Table
# --------------
CREATE TABLE login (
login_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(80) NOT NULL,
password VARBINARY(32) NOT NULL,
PRIMARY KEY (login_id),
UNIQUE(username)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# --------------
# Contact Table
# --------------
CREATE TABLE contact (
contact_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
telephone VARCHAR(60) DEFAULT NULL,
mobile CHAR(10) NOT NULL,
email VARCHAR(80) DEFAULT NULL,
PRIMARY KEY (contact_id),
UNIQUE (email)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You must provide ON clause which define the relationship on how the two tables are related with each other.
SELECT username, email
FROM login
INNER JOIN contact
ON login.colname = b.colName // change to your orignal colName
WHERE login.username = '$username' OR
contact.email = '$email'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
An alternative way to do this without checking on the value on the tables is by enforcing UNIQUE constraints on column of the table, ex
ALTER TABLE login ADD CONSTRAINT tb_uq UNIQUE (username);
ALTER TABLE contact ADD CONSTRAINT tb_uq1 UNIQUE (email);
when the two alter statements has been successfully executed,you cannot insert value if it already exists on that column.
UPDATE 1
SELECT COUNT(*)
FROM
(
SELECT userName as Value FROM Login
UNION
SELECT email as Value FROM contact
) s
WHERE VALUE IN ('$username','$email')
if the query above will return greater than 0, it means that value(s) already exists.
UPDATE 2
SELECT *
FROM
(
SELECT userName, NULL AS email FROM Login
UNION
SELECT NULL AS username, email FROM contact
) s
WHERE username = '$username' OR email = '$email'
Currently, your query selects every row from both tables as long as there is a single match for one or the other. You can get matching rows from both tables simultaneously:
SELECT username FROM login WHERE username = '$username'
UNION ALL SELECT email FROM contact WHERE email = '$email'
...and also with separate queries.
Your queries are vulnerable to SQL injection.
You are really checking 2 different things. A single query doesn't make sense, at least not a join. I suggest union instead:
select 'username' as exists from login
where username = '$username'
union all
select 'email' as exists from contact
where email = '$email'
This will return a table with a column called exists and a row for each element that exists. Here is what you would get back if both username and email exist:
EXISTS
username
email
Where you run this query, you already know what the username and email they entered are, so there is no point in returning those values from the table.
As others have pointed out, you have a big security hole if $username and $email are being passed in directly from the user. You definitely have to handle that somehow.
Every Inner join clause needs to have a predicate or "ON" condition to specify the rule or rules to be enforced when Joining the two tables...
the query needs an "ON" clause after the Inner Join. I'm not sure what that condition should be, but, as an example....
$q = "SELECT username, email FROM login
INNER JOIN contact
On contact.username = login.userName
WHERE login.username = '$username' OR contact.email = '$email'";
your join have a problem , because you should determine column wich you want join on it!
for example
NNER JOIN contact
On contact.id= login.contactId

Create mysql table from PHP array

A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.
I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.
$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';
while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());
**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.
For one, this
'CREATE TABLE $table'
will NOT fill in $table, but will be LITERALLY
CREATE TABLE $table
use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql. There might be more, but probably easily discoverable trough mentioned debugging...
You apparenty have an extra trailing comma:
CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
col1 INT,
col2 INT,
-- ^ here
)
1
change the single quotes (') to double quotes (") for your query.
2
or use dot operator (.) to append php variable.
$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';
// Output
SELECT * FROM mytable
SELECT * FROM $tableName
You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.
If you are trying to get rid of the trailing slash you can also do this by using a counter.
$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
$query .=" ".$listing[0];
if ( $key+1 != $fieldsCount )
{
$query .=',';
}
}

PHP and MySQL SELECT problem

Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.

Categories