cast text field to array in mysql select query - php

I have a table in MySQL database. In that table there is a text field called 'selection' that hold numbered values, separated by a pipe char (example: 44|5|23|546|.....). I also have a php array: $values = array(63,35,7,5);
I need to refer to the 'selection' field as array of options (separated by '|') and select only the rows that contain at least one of the number in $values array.
I hope i explained my problem accurately enough, because my English is very poor... Thanks.

If you want to get row that contains at least one number in $values array, the SQL looks like this:
$values = array(63,35,7,5);
foreach ($values as $value) {
$sql = "select * from tablename where selection like '%{$value}|%' or '%|{$value}%'";
}

If the values in the array are in the appropriate order for search already, you can build your query with something like this:
$selection_searched = implode('|', $values);
$query = "SELECT * FROM your_table WHERE selection = '$selection_searched'";
Beware that you would probably want to validate the array $values fisrt, to check if it isn't empty, etc. Check out the manual for: http://php.net/implode

Related

PHP, MySQL - Return which value was used when input is an array?

I'm running a PDO query, something like:
$inputArr = array(val1, val2, val3, ...);
$qMarks = str_repeat('?,', count($inputArr) - 1) . '?';
$stmt = $db->prepare("SELECT id, name, type, level
FROM table
WHERE name IN ($qMarks)");
$stmt->execute($inputArr);
... parse the rows that have been returned
And this works exactly as expected, no hang-ups or anything.
My problem is that I need to know which value from $inputArr was used to get each row returned.
I've tried
WHERE name IN ($qMarks) AS inputVal
and
WHERE name IN ($qMarks AS inputVal)
but those crash the query.
How can I determine which input array value was used to return each row in the output?
EDIT 1
Yes, I understand that the input search value would be name, for this particular case, but the query above is only for demonstration purposes of how I am putting the search values into the query.
The actual is much more complex, and returns any name value with is close (but not always identical).
The AS keyword is not going to work as you expect it. It's mainly used for aliasing subqueries. You can't (to my knowledge) use it in a WHERE clause.
The scenario you've outlined should have the 'name' in $row['name']. If it was a different variable that you wanted to see, you'd simply add it in your SELECT clause.
Great question, and simple answer:
The WHERE name IN $qMarks)"); part of your code is only obtaining the values in your database that are matching your array, so what you can do is see which values of name are present in the row you fetched. For example:
$rows_fetched = $stmt->fetchAll(PDO::FETCHASSOC);
$inputArray = array();
foreach($rows_fetched as $value)
{
$inputArray[] = $value['name'];
}
print_r($inputArray);//printing the results
Now you have the array $inputArray with all the values used to return each row in the output. Let me know if that worked for you!

Converting exploded array into string

In the project that I am creating, I have a mysql column that is an array of different pieces of data from the database. These pieces of data have info that I want to display. In order to separate these items in the array I used,
$get_query = mysql_query('Select array FROM data');
while($dataRow = mysql_fetch_assoc($getfrnd_query)) {
$array = $dataRow['array'];
if($array != "") {
$data_from_array_column = explode("," $array);
$getdata = mysql_query("SELECT * FROM info WHERE item = $data_from_array_column");
//Then I used a mysql_fetch_assoc to get data based on the item.
}
}
When I run this code, I get an error "Array to string conversion on the line with $getdata".
Is there any way to get this to work?
Thank you.
The problem is that explode returns an array containing the strings in between the character(s) you used as a delimiter (, in your case), not a string.
PHP is getting mad because it doesn't know how to convert your array to a string automatically. So, you will need to convert it yourself. The options are:
You want to select the row where item is equal to the nth element in the array, $data_from_array_column. If this is the case, you need to insert the following line of code after your explode:
$data_from_array_column = $data_from_array_column[0];
If you want to select where it matches any of the elements in the $data_from_array_column array, it will get more complicated. You would need to add this line after the explode:
$data_from_array_column = implode("' OR item='",$data_from_array_column);
and change your query on the next line to:
$getdata = mysql_query("SELECT * FROM info WHERE item='$data_from_array_column'");
This will create a MySQL query that looks some thing like this:
SELECT * FROM info WHERE item='foo' OR item='bar' OR item='bla'

Split comma-separated input box values and then store in database

I have a text input box where you can type tags seperated by commas. I want to store these tags separately in a table but I have no idea how to do that.
I know I have to seperate the tags after they are posted so I now have this
$array = explode(',', $_POST['tag']);
Is this a good start and how do I have to go on after that?
Creating array from your input field as in your code
$array = explode(',', $_POST['tag']);
Create a mysql multi insert query using foreach loop
simillar to this:
$id=mysqli_insert_id($con);//get your project id here
$sql="";
foreach($array as $tag_name){
//modify below to add $id along with $tag_name
$sql.="('{$id}','{$tag_name}'),"; // you need to remove last comma else it will throw mysql error
}
if($sql!=""){
//rtrim to remove last ',' from string.
$sql=rtrim($sql,',');
$sql="INSERT INTO tags_tbl (project_id,tag) VALUES {$sql};"`
}
now use mysqli_query($con,$sql) to insert values in database

Remove a loop to find existing numbers in database to one single query

I am sending an array of numbers separated by commans to server. Basically on server database I have a field that cotains numbers.Server side code checks which numbers are in database and send me the array of those numbers.
Following code is what I am using...
public function already_user()
{
$contacts=$this->input->post('contact');
//$contacts is an array.
$user= explode(',',$contacts);
foreach($user as $number)
{
$data = array (
'username' =>$number
);
$usernumber = $this->chat_model->get(array('username'=>$number)); // a simple query to datbase that check if number exists in database column or not.
if(!$usernumber==""){
$value[]=$usernumber;
}
}
echo json_encode($value);
}
Only drawback about this code is , its extremely slow.... If i have 1000+ numbers it takes a minute.since its a loop Is there any way to fasten this up. Any single mysql query??
Why don't you just write a single query? Parse the string to get an array and query the table in a single go.
$contact_array = array_map('trim', explode(', ', $contacts));
$all_usernumbers = $this->chat_model->get(array('username IN'=> $contact_array));
which should (depending of what your chat_model->get() accepts), translate to:
SELECT * FROM your_table WHERE username IN ('123', '345')
This is all pseudocode since I don't know what your framework accepts but the SQL query above should be valid.

How to use PHP Array in MySQL Select statement with BETWEEN?

I am looking to use the contents of an array
$arr =array(24,28,30,34, 40);
and pass these into the where clause of a MySQL select statement, all my research has shown this done by using IN to pass in all the array values in one go.
I need to pass in each array element one at a time and then echo out the results of the SQL statement one at a time as the select statement is updated with the next array element.
New to programming and PHP so just need a little example to get me started...
Thanks to Zad highlighted the real issue
I need to pass each array value individually to a SQL statement as these need to be utilised in Where clause with BETWEEN, eg. WHERE age BETWEEN $array1 AND $array2 in order to determine count over an age range
thanks for all the input
You can use the implode function to build the string that contains the list;
$arr =array(24,28,30,34, 40);
$query = 'SELECT * FROM mytable WHERE id IN (' .implode($arr, ', '). ' )';
echo $query;`
http://codepad.org/tLPZxq8P
http://mx2.php.net/manual/en/function.implode.php
try it with escaping the argument
foreach($arr as $array_element) {
$query = 'SELECT * FROM table WHERE field = \''.mysql_real_escape_string($array_element).'\'';
//your statement
}
You can use a foreach function:
// make connection to mysql server
foreach ( $arr as $element ) {
$statement = "SELECT whatever FROM wherever WHERE something = $element"; // maybe a little validation here wouldn't hurt either
// execute statement
// process results
} // end of foreach
// close connection
$arr =array(24,28,30,34, 40);
$a = 'SELECT * FROM foo WHERE bar IN('.implode(',',$arr).')';
Edit: I'll admit, I didn't fully read the question, the title is misleading - consider changing that.
I need to pass in each array element one at a time and then echo out
the results of the SQL statement one at a time as the select statement
is updated with the next array element.
Could you explain how the scenario a bit better?

Categories