How to make form with many query PHP MYSQL - php

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));

Related

How to ignore null value while fetching the data from database table php mysql

How to ignore null value while fetching the data from database table php mysql. Anyone please help me
My mysql query is :
$sql = "SELECT DISTINCT cuid FROM temp_donor_list WHERE donor_no='$name'";
Try this below code
$sql = "SELECT DISTINCT cuid FROM temp_donor_list WHERE donor_no='$name' and cuid!='' and donor_no!=''";
If your field contains NULL value then you can use IS NOT NULL condtion.
If your field contains blank string then you can use <> opertor
SELECT DISTINCT cuid FROM temp_donor_list WHERE donor_no='$name' AND cuid IS NOT NULL AND cuid<>''

trying to INSERT NULL if input field left blank

I'm trying to insert NULL into the mySQL databse with PHP.
I've got:
$myVariable=$_POST[inputfield];
if(!is_numeric($myVariable) || $myVariable==0){
$myVariable=NULL;
}
My database field is decimal, and IS NULL has been set. It keeps reverting to 0.00 if input is left blank. How do I set NULL if left blank, so I can call a php if NULL function?
Edit Calling if NULL in decimal is not correct?
<? if ($debit==NULL || $debit=="0.00") {echo 'Awaiting Cost';}
elseif ($debit != NULL || $debit!="0.00") { echo "£$debit";}?>
This displays my message correctly, so if if NULL is useless for a decimal i'll just leave 0.00. Is this hacky?
SQL structure for those who asked:
`myTableField` decimal(10,2) default NULL,
If you are composing an SQL statement by appending the value of the $myVariable variable, then you should look if it's NULL or not and modify the SQL statement accordingly.
For example, if your code is something like:
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
then you should change it to something like:
if (is_null($myVariable)) {
$sql .= "myVariable = NULL";
} else {
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
}
Try it on the SQL side:
$sql = "INSERT INTO `table` (`field1`) VALUES (IF($myVariable == 0, NULL, $myVariable))";
try:
$myVariable="NULL";
.
if your code is:
$val=NULL;
mysql_query("SET #v=$val");
the MySQL got the string:
SET #v=0;
it's like using :
echo "SET #v=$val";
you can filter field's data in MySQL itself, using a TRIGGER:
CREATE TRIGGER table1_update BEFORE UPDATE ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);
CREATE TRIGGER table1_create BEFORE INSERT ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);

Filling NULL value again on deletion or updation

I have updated certain field in my database & that field has default value as NULL. How can I again fill NULL if field is emptied or deleted. As during this updation blank value is filled in database and of course that is not NULL. Is filling NULL instead of blank value good?
Using php how can I do that? Suppose I have condition if code
if(!empty($photo))
{ $a in database;
}
But in this condition if $photo is empty it will fill blank value of $a... Let me know to fill NULL in database.
You just have to write null, and not an empty value, to your database.
You SQL query would look like this :
update your_table
set your_field = NULL
where ...
instead of :
update your_table
set your_field = ''
where ...
To switch between those two queries, you might need some condition in your PHP code, depending on how it's organized ; maybe like this :
if (empty($photo)) {
// query to set the field to NULL
}
else {
// query to update the value
}
Note that if you have no value to store for a row in your database, you might also want to just delete that row :
delete from your_table
where ...
Of course, it's up to you to determine which is the best for your application : a row with a NULL value, or no row.

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