Dynamic SQL Command - php

I want to be able to get only values where there is a '1' in multiple columns.
My column names are stored dynamically in a variable though.
How would I go about this?
This is what I have.
Columns are layed out like this
$Columns = "Computer, Science, Algebra, Biology, Networking"; //This is Dynamic so $Columns may be like this next time $Columns = "Biology, Networking";
$SQL = "SELECT * FROM users WHERE '1' IN(".$Columns.")";
Right now, it selects any users that have a "1" in any of the columns
I only want to retrieve the users that have a "1" in ALL of the variables in the array $Columns not just one of them

Since your $columns variable can be different sizes, you will need to build your sql statement based on the number of columns in the array in a for loop:
// SET your first column IN
$sql = "SELECT * FROM users WHERE '1' IN (".$Columns(0).")"
//Run the for loop to build sql on all subsequent columns
// size of will give you the number of columns in your array
$max = sizeof($columns);
for($i = 1; $i < $max;$i++)
{
//Use the "AND" to make sure "1" is in all columns
$sql.=" AND '1' IN (".$Columns($i).")
}
$sql.=";"
My code may not be perfect, but should get you in the right direction.

Related

Add values from MySql database to an array through a loop

I have been trying to set a while loop to add all the ids in which the user has 20 days into an array. Currently, it displays an error of undefined offset. How can I code the code so that it first gets the id of the first row with 20 days in the lastSeen column, then, second, the ids of the second row and then adds them to the array?
$get_email = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'" );
$email = mysqli_fetch_array($get_email);
$num_days = mysqli_num_rows($get_email);
$i = 1;
$array_id = array();
while($i <= $num_days){
array_push($array_id, $email[$i]);
$i = $i + 1;
}
First of all, your code is confusing. You get IDs from the database but the names of the variables tell "email". Try to be consistent, it will help you later, when you read this code again.
Since you don't do any processing with the values you get from the database, you can use mysqli_fetch_all(). It returns all the rows from the record set at once in an array. Passing MYSQLI_ASSOC as its second argument tells it to use the column names (from the SELECT clause of the query) as keys in the arrays it creates from each row of the result set.
Next, the PHP function array_column() extracts only the values of column id into a new array that contains exactly the values you need:
$result = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'");
// Get all the rows, indexed by column names
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Get only the 'id' column
$ids = array_column($rows, 'id');

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Dynamically assign alias to all the field names in msyql query

I have 2 tables in mysll DB. Both tables have few fixed and few dynamic columns (Fields / Schema). I want to join both these tables with following query:
SELECT *
FROM `cd` cd
LEFT JOIN cd_n cn ON cd.id = cn.fk_cd
And I want to result as
CD_Column1 CD_Column1 CD_Column3 ...... CN_Column1 CN_Column2 CN_Column3 .....
value value value ...... value value value ...
value value value ...... value value value ...
Where ..... is dynamic column names of both the tables.
So the case is I dont know the column names because they are dynamic and I want rename (alias) it on query level. Please let me know how can I do this?
You would need to query the information_schema to get the column names of that two tables. Lets assume You would have the cd column names stored in the array $cd_columns and the cd_n column names in the array $cdn_columns.
Then in PHP when creating the query loop through the column arrays and do something like this:
$sql = 'SELECT ';
// add the cd columns
$i = 0;
foreach($cd_columns as $col) {
$sql .= "{$col} AS CD_Column{$i},";
$i++;
}
// add the cd_n columns
$i = 0;
foreach($cdn_columns as $col) {
$sql .= "{$col} AS CN_Column{$i},";
$i++;
}
// remove the trailing comma
$sql = trim($sql, ',');
// continue the SQL
$sql .= ' FROM ...';
Was this helpful?

Checking if a value is in the db many times

I have a table A, with just two columns: 'id' and 'probably'. I need to go over a long list of ids, and determine for each one whether he is in A and has probability of '1'. What is the best way to do it?
I figured that it would be best to have 1 big query from A in the beginning of the script, and after that when I loop each id, I check the first query. but than i realized I don't know how to do that (efficiently). I mean, is there anyway to load all results from the first query to one array and than do in_array() check? I should mention that the first query should had few results, under 10 (while table A can be very large).
The other solution is doing a separate query in A for each id while I loop them. But this seems not very efficient...
Any ideas?
If you have the initial list of ids in array, you can use the php implode function like this:
$query = "select id
from A
where id in (".implode (',', $listOfIds).")
and probability = 1";
Now you pass the string as first parameter of mysql_query and receive the list of ids with probability = 1 that are within your initial list.
// $skip the amount of results you wish to skip over
// $limit the max amount of results you wish to return
function returnLimitedResultsFromTable($skip=0, $limit=10) {
// build the query
$query = "SELECT `id` FROM `A` WHERE `probability`=1 LIMIT $skip, $limit";
// store the result of the query
$result = mysql_query($query);
// if the query returned rows
if (mysql_num_rows($result) > 0) {
// while there are rows in $result
while ($row = mysql_fetch_assoc($result)) {
// populate results array with each row as an associative array
$results[] = $row;
}
return $results;
} else {
return false;
}
}
for each time you call this function you would need to increment skip by ten in order to retrieve the next ten results.
Then to use the values in the $results array (for example to print them):
foreach ($results as $key => $value) {
print "$key => $value <br/>";
}
Build a comma separated list with your ids and run a query like
SELECT id
FROM A
WHERE id IN (id1, id2, id3, ... idn)
AND probability = 1;
Your first solution proposal states that:
You will query the table A, probabyly using limit clause since A is a table with large data.
You will place the retrieved data in an array.
You will iterate through the array to look for the id's with probability of '1'.
You will repeat the first three steps several times until table A is iterated fully.
That is very inefficient!
Algorithm described above would require lots of database access and unneccessary memory (for the temporary array). Instead, just use a select statement with 'WHERE' clause and process with the data you want.
You need a query like the following I suppose:
SELECT id, probably FROM A WHERE A.probably = 1
If i understood you correctly, you should filter in the SQL query
SELECT * FROM A WHERE A.probably = 1

Categories