This code checks if $value (array) is set in the database as 1. The foreach loop saves all the founding matches into the array $products. Now I have all the fields in the database which have the value 1 but that's not really what I want, because if the field 'dog' equals 1 and the field 'cat' equals NULL, I still have the value of 'dog' in my array. It only should get to the array when BOTH equal 1.
For simple variables you can use the && or AND operator to check if all keys have the same value but how do I do this with an array?
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
var_dump($value);
if($result = $db->query("SELECT * FROM produkte WHERE `$value` = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image, 'link'=>$row->link) );
}
}
}
else {
array_push($products, 'error');
}
}
Change your SQL statement such that all checked values are equal to 1.
You can append a " = 1 AND " to each value then use them in your query.
<?php
$arr = ['field1', 'field2', 'field3'];
$condition = join(' = 1 AND ', $arr) . ' = 1';
The output would be "field1 = 1 AND field2 = 1 AND field3 = 1". You can then use $condition in your query.
$db->query("SELECT * FROM produkte WHERE $condition")
UPDATE:
To cope with fieldname containing spaces you would need to wrap each fieldname with backticks so change this line
$condition = '`' . join('` = 1 AND `', $arr) . '` = 1';
Related
I got an array of ids that I want to use inside an IN statement (sql). However this can only be done when it is written correctly, for example: IN ('12', '13', '14')
How can I change an array of ids into that format? This means adding quotes around every number, and after every number surrounded by quotes a comma, except for the last one in the array.
My code:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
I later want to use it like this:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";
Do this as a single query! SQL engines have all sorts of optimizations for working with tables, and doing the looping in your code is usually way more expensive.
The obvious query for your purposes would be:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;
Use implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
Have you tried to implode()?
Use ", " as glue. You will have to edit the string yourself to add a " at the beginning and end.
More info: http://php.net/manual/en/function.implode.php
Alternatively you can use single join query, like this.
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1
If the column's type in the DB is integer you do not actually need to quote the values, but in case it isn't, you can use array_map to quote every item in the array, then implode to join them with commas:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
Result:
SELECT * from mytable where id in ('1','2','3','4','5')
You can do something like this:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
This will give you :
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1
I have 3 fields in database:
levelOne , levelTwo, levelThree // Table Name = levels
With values:
levelOne = 300,
levelTwo = , // This field is empty
levelThree = , // This field is empty
Now I have a variable which has to be compared with the respective fields.
$var = L1_200;
Now L1_200 means its a level 1 value so it has to be compared with levelOne field in a query and vice versa. SO how can I write the query?
Try this code:
<?php
$var = 'L1_200';
$sql = 'select * from table_name where 1 ';
$arr = explode('_', $var);
if($arr[0] == 'L1'){
$sql .= 'AND levelOne = \''.$arr[1].'\'';
} else if($arr[0] == 'L2'){
$sql .= 'AND levelTwo = \''.$arr[1].'\'';
} else if($arr[0] == 'L3'){
$sql .= 'AND levelThree = \''.$arr[1].'\'';
}
Now use $sql
I have an array in PHP that is looping through a set of names (and a corresponding quantity). I would like to print the ones found in a MYSQL database table (to which I've succesfully connected). I'm currently using the code:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
echo $quan." ".$row['name']. "\n";
}
}
For some reason, this only prints the last quantity and name in the array. Help?
For example, if the array has key-value pairs of {A-4, B-2, C-3}, and table contains {A, B, D} as names ... it'll only print "2 B".
Change the code to the following:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
You have to loop through the result. By the way, stop using mysql_query()! use MySQLi or PDO instead ( and be careful of SQL Injection ; you can use mysqli_real_escape_string() to handle input parameters ). For MySQLi implementation , here it is :
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
And rather "\n", I prefer using PHP_EOL ( as shown above )
And as the comment suggests, the SQL statement can be executed once, as follow:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
e.g. in $arr contains "peter", "mary", "ken", the Query will be:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
sidenote: but I don't understand your query. You only obtain the name back from the query? You can check number of rows, or you can even group by name, such as:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
to get what you want.
UPDATE (again): based on the comment of OP, here is the solution :
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
The above query will show the name appearing in the table only. Names not in table will not be shown. Now full codes ( be cautious of SQL Injection , again )
I want to add an array to my db. I have set up a function that checks if a value in the db (ex. health and money) has changed. If the value is diffrent from the original I add the new value to the $db array. Like this $db['money'] = $money_input + $money_db;.
function modify_user_info($conn, $money_input, $health_input){
(...)
if ($result = $conn->query($query)) {
while ($user = $result->fetch_assoc()) {
$money_db = $user["money"];
$health_db = $user["health"];
}
$result->close();
//lag array til db med kolonnene som skal fylles ut som keys i array
if ($user["money"] != $money_input){
$db['money'] = $money_input + $money_db;
//0 - 20
if (!preg_match("/^[[0-9]{0,20}$/i", $db['money'])){
echo "error";
return false;
}
}
if ($user["health"] != $health_input){
$db['health'] = $health_input + $health_db;
//0 - 4
if (!preg_match("/^[[0-9]{0,4}$/i", $db['health'])){
echo "error";
return false;
}
if (($db['health'] < 1) or ($db['health'] > 1000))
{
echo "error";
return false;
}
}
The keys in $db represent colums in my database. Now I want to make a function that takes the keys in the array $db and insert them in the db. Something like this ?
$query = "INSERT INTO `main_log` ( `id` , ";
foreach(range(0, x) as $num) {
$query .= array_key.", ";
}
$query = substr($query, 0, -3);
$query .= " VALUES ('', ";
foreach(range(0, x) as $num) {
$query .= array_value.", ";
}
$query = substr($query, 0, -3);
$query .= ")";
If the id field is already set to be an Auto-Increment value, you do not need to declare it in the INSERT command (it is just assumed as not being over-ridden, and will fill with the auto-incremented value).
Assuming that $db is an an associative array, where the element keys are the same as the SQL field names, and the element values are the desired values for those SQL fields.
# Sanitise the Array
$db = array_map( 'mysql_real_escape_string' , $db )
# Create the SQL Query
$query = 'INSERT INTO `main_log` '.
'( `'.implode( '` , `' , array_keys( $db ) ).'` ) '.
'VALUES '.
'( "'.implode( '" , "' , $db ).'" )';
That should produce an SQL query which will perform the required work. Plus it should reduce the possibility of SQL Injection attacks...
(Note: The line breaks, etc. above are for readibility only, and can be removed.)
I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$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>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...