How to select all data from all tables? - php

I have a database table called stories. It only has one row---story.
How do I return all the stories in a, concatenated in a single string variable?
I thought it would be merely
$sql = mysql_query("select * from stories");
Incorrect?

You could use GROUP_CONCAT():
SELECT GROUP_CONCAT(story) FROM stories;
This will return a concatenated string with each story separated by an ',' character.
If you would like to remove the separator you can use the following syntax:
SELECT GROUP_CONCAT(story SEPARATOR '') FROM stories;

Try this:
select GROUP_CONCAT(story_column) as stories from stories
Here story_column is name of column where stories are saved in table.
It will give you all stories in a single string with concatenating.

I don't understand you question, but this may help you.
SELECT CONCAT(`col1`, ' ', `col2`,' ',`col3`) FROM `table`

Related

MySQL + Alternative to IN() clause that returns row for each item?

OK.. so I had a post here:
MySQL/PHP/PDO + How to get a row for each (duplicate) entry in IN() clasue?
Apparently... there is no solution. (or so I'm told)..
So is there an alternative solution to using the IN() clause? One that DOES in fact return a row for each item passed in...regardless if its a duplicate entry or not?
I have suggestions about using a (self) JOIN.. or possibly even EXISTS... but I am not clear on how I can go about adjusting my current dynamic query using such suggestions?
$qMarks = str_repeat('?,', count($brandlist) - 1) . '?'; //create '?' mark placeholders for query, remove last comma and replace with '?'
//preserve IN() order
$displayList_sql = "SELECT * FROM $tablename WHERE CONCAT(brandname, ' ', dosage) IN ($qMarks) ORDER BY FIELD(CONCAT(brandname, ' ', dosage),'". trim(implode("','", $brandlist))."')";
$displayList_stmt = $conn->prepare($displayList_sql);
$displayList_stmt->execute($brandlist);//make note of passing in array as param to execute() call
Can this be altered to use a JOIN or EXISTS (anything) so that it returns a row for each item? (which is a dynamically posted array?)
It's not exactly pretty, but you can "convert" your list to a subquery and join that against the actual table you want to query.
SELECT t.stuff
FROM (SELECT 'in item 1' AS item
UNION ALL SELECT 'in item 2'
UNION ALL ...
) AS inList
INNER JOIN $tablename AS t ON inList.item = CONCAT(t.brandname, ' ', t.dosage)
ORDER BY ...
My guess is there is probably some php methods you can use to explode/split the variable you had used to populate the IN list to create the SELECT ... UNION ALL ... subquery.
Worst, most primitive case (in pseudo code), assuming a simple comma-separated list:
theList = "SELECT " + REPLACE(theList, ',', ' AS item UNION ALL SELECT')
If query length becomes an issue, another option is to create a temp table to store the IN list in, and then join against that. (This technique can also sometimes be used to make the query faster; since the temp table can be indexed to help with the join operation.)

SQL get an id from a column where ids separated by commas

I have a column named id with a bunch of ids separated by commas like this:
asdaxxdfd2,wwfsfdssdfsd6,sdfdsfdsed2,23445rr55
I need to match an id from the column to an existing $user_id
Trying this didn't do it:
"SELECT id FROM my_table WHERE id LIKE '%" . $user_id . "%'";
Not sure what else I can do.
Thank you.
"SELECT id FROM my_table WHERE concat(',', id, ',') LIKE '%," . $user_id . ",%';"
should do it.
But I also strongly recommend to normalize the schema.
Your question is a little bit ambiguous, I don't know if this solution is what you intends:
SELECT REGEXP_SUBSTR(id, '[^,]+', 1, 1) COLUMN_1,
REGEXP_SUBSTR(id, '[^,]+', 1, 2) COLUMN_2,
FROM my_table;
or just
SELECT id
FROM my_table
WHERE id LIKE '%wwfsfdssdfsd6%'
SELECT REGEXP_SUBSTR(id," . $user_id . ") UserID FROM my_table;
This will return the matching user id but again using a database with values stored in a single row is never a good idea.
SELECT * FROM tbl WHERE id REGEXP "[[:<:]]$user_id[[:>:]]";
Those match "word boundaries", thereby handling beginning and end of string.
But, without normalizing there is no way to make a query that runs faster than a full table scan.

Using Replace in SELECT * statement

How can I work this REPLACE statement I'm using in the following, into my SELECT statement below ? The update works perfectly, but need the same code in the SELECT.
$sql1 = ("UPDATE $table SET notes=replace(REPLACE(notes,CHAR(13),' '),CHAR(10),' ') WHERE year='$year'");
$sql2 = "SELECT * FROM $table WHERE SUBSTR(week_start_date,-4)=$startDate AND week_num = '$week' AND archived!='yes' ORDER BY fn,ln";
Thanks for any assistance.
If you have data in your table that has CRLF that you want to REPLACE with ' ', you can't use the SELECT * notation - you have to tell it which column you want to replace the characters in. You'll have to do something like this:
$sql2 = "SELECT REPLACE(REPLACE(notes, CHAR(13), ' '), CHAR(10), ' ') as fixed_notes FROM $table ...`
In general, it's best to avoid using SELECT *, and always to specify the columns you want (as well as any scalar functions you want to run on said columns) explicitly. This way, if the table definition adds more columns, you don't start getting data you never intended to process; and if a column gets dropped, you'll know that was the cause rather than something else in your presentation layer. It also means that it'll be possible to manipulate the individual columns in the statement where appropriate.
If you can live with these limitations, and you don't mind having the column appear twice, you could do this:
$sql2 = "SELECT *, REPLACE(REPLACE(notes, CHAR(13), ' '), CHAR(10), ' ') as fixed_notes FROM $table ...`

Can I remove an apostrophe from an SQL search (WHERE clause)?

I have a query in SQL (Mysql) using a where clause.
SELECT * FROM TABLE WHERE name = 'Bristols';
Now I know that there's a row in the table containing Bristol's with an apostrophe, but not one without an apostrophe. However I want to return the row anyway. The problem is that I can only feed the query a value without an apostrophe: Bristols - is there any way within the query to remove the apostrophe from the field the query is searching?
SELECT * FROM TABLE
WHERE replace(name, '''', '') = 'Bristols'
There are several ways to accomplish this:
See Fiddle
Regex:
SELECT *
FROM cities
WHERE name REGEXP 'Bristol\'?s';
Replace:
SELECT *
FROM cities
WHERE 'Bristols' = replace(name,'\'','');
Explicit Matching:
SELECT *
FROM cities
WHERE name IN('Bristols','Bristol''s');
You have Two possible outlooks:
First:
SELECT * FROM TABLE WHERE name LIKE '%Bristol%' // Gather data like: BrISTOLS, Bristols, Bristol, Bristol's,
Second:
SELECT * FROM TABLE WHERE replace(name,'''','') = 'Bristols'

Mysql LIKE clause and separate words in a field

I currently use a mysql statement like the one below to search post titles.
select * from table where title like %search_term%
But problem is, if the title were like: Acme launches 5 pound burger and a user searched for Acme, it'll return a result. But if a user searched for Acme burger or Acme 5 pound, it'll return nothing.
Is there a way to get it to return results when a users searches for more than one word? Is LIKE the correct thing to use here or is there something else that can be used?
You could use a REGEXP to match any of the words in your search string:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]](', REPLACE('Acme burger', ' ', '|'), ')[[:>:]]')
Please notice that this will not be very efficient. See fiddle here.
If you need to match every word in your string, you could use a query like this:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]]', REPLACE('Acme burger', ' ', '[[:>:]].*[[:<:]]'), '[[:>:]]')
Fiddle here. But words have to be in the correct order (es. 'Acme burger' will match, 'burger Acme' won't). There's a REGEXP to match every word in any order, but it is not supported by MySql, unless you install an UDF that supports Perl regexp.
To search for a string against a text collection use MATCH() and AGAINST()
SELECT * FROM table WHERE MATCH(title) AGAINST('+Acme burger*')
or why not RLIKE
SELECT * FROM table WHERE TITLE RLIKE 'Acme|burger'
or LIKE searching an array, to have a compilation of $keys
$keys=array('Acme','burger','pound');
$mysql = array('0');
foreach($keys as $key){
$mysql[] = 'title LIKE %'.$key.'%'
}
SELECT * FROM table WHERE '.implode(" OR ", $mysql)
What you need to do is construct a SQL such that, for example:
select * from table where title like "%Acme%" and title like "%burger%"
In short: split the string and create one like for each part.
It might also work with replacing spaces with %, but I'm not sure about that.
The best thing is thing use perform union operation by splitting your search string based on whitespaces,
FOR Acme 5 pound,
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME 5 POUND%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%5%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%POUND%'
Find out a way to give the first query a priority. Or pass the above one as four separate queries with some priority. I think you are using front end tp pass query to data bases, so it should be easy for you.
<?php
$search_term = 'test1 test2 test3';
$keywords = explode(" ", preg_replace("/\s+/", " ", $search_term));
foreach($keywords as $keyword){
$wherelike[] = "title LIKE '%$keyword%' ";
}
$where = implode(" and ", $wherelike);
$query = "select * from table where $where";
echo $query;
//select * from table where title LIKE '%test1%' and title LIKE '%test2%' and title LIKE '%test3%'

Categories