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

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.

Related

Increment remaining row values in a column based on changing one value

I am trying to create a round robin scenario when new leads come in.
When a lead comes in, the following table named "round_robin" will find the position '1' and send the lead data there
Name Type Attributes Null Default Extra
id int(11) No None AUTO_INCREMENT
on_off text Yes NULL
cname text Yes NULL
position int(11) Yes NULL
email varchar(100) Yes NULL
I have some knowledge of PHP so if some coding I used is way off, thats likely why.
This is the code I've started on.
$round_robin_companies = "SELECT * FROM round_robin";
$position_one = "SELECT position FROM round_robin WHERE postion = '1' ";
$query = "SELECT * FROM round_robin WHERE position = '$position'";
$result = mysql_query($query);
if ($result === 1) exit();
else {
UPDATE $position_one SET position='$row_count';
while ($query <= $row_count) {
$row_count++;
}
}
Basically, when a new row is added in a table called leads, I need Company One position to change to $row_count (3) and all the remaining positions to increment down one.
So Company Two position would be 1 and be next in the queue and Company Three would become 2. I want to use row count because I will be adding more companies in the future.
id on_off cname position email
1 on Company One 1 C1#email.com
2 on Company Two 2 C2#email.com
3 on Company Three 3 C3#email.com

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

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.

Checking for an empty field with MySQL

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>";
}
}
}

Categories