Php array to MySQL query condition structure - php

I have following array in PHP:
$arr = [1, 3, '4A', '5A', '5C', '2B', '2C', '2E'];
Somehow I need to convert this array to a string which look like this:
$filter = "(id like '1%') OR
(id like '3%') OR
(id like '4A%') OR
(id like '5A%' OR id like '5C%') OR
(id like '2B%' OR id like '2C%' OR id like '2E%')";
The first character of the array value indicates a unique categorie and is wrapped in parentheses.
In the end I will use this to query the database;
$sql = "SELECT * FROM list WHERE {$filter}";
Can someone help me converting this array to the correct string ? What is the best method to achieve this ?
To give you an idea of what I'm trying:
The 'id' column in my database row looks like; 1B2875. Where the first char (1) indicates a categorie and the second char (B) the subcategorie. The given array is a result of a client-side filter request.

You can use regular expressions in SQL:
SELECT * FROM list WHERE id REGEXP '^(1|3|4A|…)[0-9]+$'
The value inside the parentheses can be generated with the PHP function implode('|', $filter_strings)
Note that you should validate and escape the filter strings first to prevent the user input from manipulating the query. The function preg_quote is useful here.

Related

Fetch Casted Value from a select query into an array

I used cast in order to convert a datatype of one of the columns in my select query.
SELECT cast(user_id as varchar(255)) from cabinet
I need to fetch the result of this value into an array but it returns null value
$listData[] = array(
"member_id" => $row['cast(user_id]
);
How can I display it on array?
SQL:
SELECT cast(user_id AS varchar(255)) AS member_id FROM cabinet
PHP:
$listData = array("member_id" => $row['member_id']);
Basically, you forgot to name the cast function's return in your SQL and used some extremely weird syntax in your PHP. $Array[] = $x; adds element $x as an array item to $Array in PHP. To create a new array, you should run $Array = array();. Some programming languages do indeed force you to put square brackets after a variable's name on value assignation to specify it as an Array/String type, but PHP is not one of them.
To reference an item by key, you have to use the array's name and the key's value in square brackets ($Array[$n], where $n is an integer for arrays with integer indexes, and Array['key'] for arrays with String indexes). 'cast(user_id AS varchar(255))' is not a valid array key, you have to give the SQL function return value a name to be able to reference it as an array item.
Please let me know if this makes sense.
My answer assumes that you are familiar with mySQLi and know how to get $row['member_id'] from the query.

Parsing through database table and pulling out unique names

I have a table that is listed like this:
Table name: test
|--------------------|
|------Column 1------|
|--------------------|
|John,Raul,Matt,Tyler|
|Tim,Hannah----------|
|Zeke,Brady,Tim,Tyler|
|Elliot,Zeke---------|
|Matt,Andrew,Idda----|
...
And I need to get all of those names into a PHP array, without multiple cases of the same name.
Would I be better off getting each unique name via SQL, or should I just pull the column, and then parse through it via PHP?
The final PHP array would look like:
$test_array[0]="John"
$test_array[1]="Raul"
$test_array[2]="Matt"
$test_array[3]="Tyler"
$test_array[4]="Tim"
$test_array[5]="Hannah"
$test_array[6]="Zeke"
$test_array[7]="Brady"
$test_array[8]="Elliot"
$test_array[9]="Andrew"
$test_array[10]="Idda"
I'm not sure how I would parse each cell in the table. What would you guys do?
I agree it's best to normalize the database. However, given the situation you've described, I would perform the SQL select and use PHP to run through the results.
I'd initialize $results as an empty string:
$results = '';
Then I'd concatenate each row with $results:
$results .= $row;
Then I'd use explode() to put all of the names in an array:
$all_names = explode(',', $results);
Then I'd use array_unique() to reduces the $all_names array to unique values:
$unique_names = array_unique($all_names);
HTH.

Turn a string into an array using PHP

My session variables are
$_SESSION["listofIds"]=163,164;
$_SESSION["listofVals"]=4,3;
I want to select session values like
$_SESSION["listofIds"][0]=163;
$_SESSION["listofIds"][1]=164;
$_SESSION["listofVals"][0]=4;
$_SESSION["listofVals"][1]=3;
I tried
echo $_SESSION["listofIds"][0];
then it prints '1' i.e. first character. How can I handle this?
Also how can I get 1st element of $_SESSION["listofIds"] and 1st element of $_SESSION["listofVals"] after placing in while loop for mysql query.
Your session variables seem to be strings. Use
$IdsArr = explode(",", $_SESSION["listofIds"]);
echo $IdsArr[0];
With explode splitting the string by "," to an array.
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
now you can access the variables using listofIds[0] or listofIds[1].
First of all you should start by defining from scratch an array while placing values in the $_SESSION array. This is a better way to write code.
Anyway as all the other answers said:
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
will convert your string into an array and you will be able to access each value in different ways. Most commons:
using a foreach loop
getting the index of the item you want to use.
If you want to use the first item in a query you should get its value using the index (array starts from 0) so your value will be $listofids[0]. The same logic will apply to the other $_SESSION value.
Another good practice for programming: when you put an array value in a query string assign it to a variable before:
$id_to_search = $listofids[0];
and then use it into the query:
$sql = "SELECT * FROM your_table WHERE id='$id'";
This will save you a lot of headache with singe and double quotes.

Populate select menu from PHP/MySQL using javascript array

I have this code:
<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
</script>
<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>
it works exactly how i need it to but i am wondering if it is possible to display the column name "name" from the database in the select options as well as the code?
for example rather than just
123
to have it like this
123 - name
You'll want to rigidly separate your php and your js. The way the code is written will work as is, but is very brittle, and can break catastrophically, leading to action-at-a-distance style bugs.
For example, if your database schema were refactored to remove the code column, then your javascript would be rendered broken, with a cause that nobody would suspect.
That said, if you'd like to also display the data in the name column in the select options, you'll have to pass that data into $nominalcodes as well. Right now, it contains an indexed array of data (perhaps an int or a string), but you'll want to change that so it contains an indexed array of arrays.
So, before:
$nominalcodes = array(1,3,5,78,3,2,234);
and after:
$nominalcodes = array(
array(1, 'foobar'),
array(3, 'larry'),
array(5, 'bob'),
...
);
At this point, you'll have to refactor your javascript addOptions function so that it can properly parse an array of arrays, instead of an array of single values.

get all fields value from mysql using php

i want to know how to get all fields value search by array.
i have array that s
my table is
id content
1 zahr
2 hai
.
.
.
and so on
$a = {2,3,4,5,43,32};
i have to take the contents by this id(from array "a").
i know, i can use "for" loop for getting each element from mysql.
but i would like to use any filters or any predefined function
thanks and advance
SELECT * FROM table WHERE id IN (2,3,4,5,43,32)
the statement could be created by using implode like:
$myvar = '('.implode(',',$a).')';
and then
SELECT * FROM table WHERE id IN $myvar
use IN

Categories