Using LIKE with prepared statement - mysql

I have a statement I wish to execute to find if a column containing a string contains a certain value.
+----+------+
| id | st |
+----+------+
| 0 | 2183 |
| 1 | 5820 |
| 2 | 2984 |
| ...| ... |
+----+------+
Say I wish to find all rows where st contains a 1, I would use these where conditions:
WHERE st LIKE "%1%"
OR st LIKE "1%"
OR st LIKE "1"
OR st LIKE "%1"
But how do I do this in a prepared statement?
$ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE "%:a%"
OR st LIKE ":a%"
OR st LIKE ":a"
OR st LIKE "%:a"
");
$ps->execute(array(
':a' => $var
));
This doesn't work evidently.

The % sign must be part of $var not part of the prepared Statement. also you only need %:a% it include all other parts of your where clause
$ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE :a
");
$ps->execute(array(
':a' => "%".$var."%"
));

ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE :a");
$ps->execute(array(
':a' => "%".$var."%"
));
Try above code.
And one more thing if you require rows which contains 1 in it,then there is no requirement of 4 like condition you only can achieve using '%1%'.
Hope this will help.

Related

Choosing from multiple columns by column name stored in a column

I want to select from a table like this
|id|col_name|col1|col2|col3|col4|col5|...|col100|
| 1|col1 | 142| 241| 333| 417| 713|...| 125|
| 2|col5 | 927| 72| 403| 104| 136|...| 739|
| 3|col100 | 358| 842| 150| 125| 174|...| 103|
Select from column specified by col_name field. Something like
SELECT id,valueof(col_name) val FROM table1
which returns
|id|val|
| 1|142|
| 2|136|
| 3|103|
If you are using PHP (or modify the logic accordingly), you can do something like-
$colNames = array(col1, col5, col100); // or SELECT col_name FROM
table_name and store it in $colNames
foreach ($colNames as $val) {
$query = "SELECT $val FROM table_name WHERE col_name={$val}";
//execute this and store its result one-by-one into another array.
}
as I'm not sure if it could be done with single query.

mysql update table with values from another table?

I am trying to update my table 'supplier_stats' with the values from my other table 'supplier_change_request'.
My two tables look like the following:
Supplier_change_request
id | user_id | company_name | supplier_number
1 123 hewden V0001
Supplier_stats
Id | user_id | company_name | address | reference | supplier_number
1 123 pie n/a 12345 V0001
2 145 gates n/a 12345 V0002
Here is my MySQL:
$reference = '12345'
$query = "UPDATE supplier_stats
SET supplier_stats.company_name = (
SELECT supplier_change_request.company_name
FROM supplier_change_request
WHERE supplier_change_request.reference = '$reference' AND supplier_change_request.supplier_number = supplier_stats.supplier_number";
mysql_select_db('hewden1');
$retval = mysql_query( $query, $conn )
by my calculation this should be setting the value of company_name where supplier_number is 'V0001' in my table 'supplier_stats' to 'hewden'. However the company_name is not being updated.
Can someone please show me where I am going wrong? Thank you in advance
I think the syntax is a bit off in your query and that it should look like this (just the SQL, adapt to PHP as needed):
UPDATE supplier_stats ss
JOIN supplier_change_request scr ON scr.supplier_number = ss.supplier_number
SET ss.company_name = scr.company_name
WHERE ss.reference = '$reference'
The column reference pointed to the supplier_change_request in your sample query, but to supplier_stats in your sample data - I assumed the sample data was correct; change if not.
This query should change the company_name in supplier_stats from pie to hewden.

Perl and MySQL user input to select a row?

Suppose I have a simple database table that doesn't have an ID_KEY but has a name column. I want to display the output like this
+----+---------+
| | name |
+----+---------+
| 1 | dog |
| 2 | cat |
| 3 | penguin |
| 4 | lax |
| 5 | whale |
| 6 | ostrich |
+----+---------+
Then have a <STDIN> for like, say, 3 to select penguin. 3 is just the line number that appears when you do the select call.
Is there any way to do this, or is it only possible with an id key associated and then a subsequent select statement matching that id key?
I misunderstood you at first but I've caught on. But it doesn't make much sense, as when you're entering a number into a Perl program you won't be working with the MySQL command-line tool, and won't be able to see what numbers to enter..
What you need to do is to write your Perl program so that it prints all the name fields from the table together with a line number. Then your program can translate from an input animal number to its name because it knows what it printed.
Something like this would work. Of course you will have to set the name, IP address and credentials correctly so that DBI can connect to the database.
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect(
'DBI:mysql:database=animal_test',
'username',
'password',
{ RaiseError => 1 },
);
my $names = map #$_, $dbh->selectall_arrayref('SELECT name FROM animals');
for my $i ( 0 .. $#$names ) {
printf "%3d: %s\n", $i+1, $names->[$i];
}
print "\n";
print "Enter animal number: ";
my $animal = <>;
chomp $animal;
my $name = $names->[$animal-1];
printf "Animal chosen is %s\n", $name;
Option 1 - You would have put a id field in the DB if you want to find by integer 3 because row 3 will not always be penguin from an SQL query.
Option 2 - Dump the data into and array or hash and use the index of that to find the item from with in the variable and not the DB when 3 is captured from STIN.
Just use query:
my $select = $dbh->prepare('
SET #id:=0;
SELECT name,
#id = #id+1
FROM table
');

mysql join 2 table to select one row fields with multiple rows

I need to join two table as follows - table 2 'value' on table 1 'price_1', 'price_2' & 'price_3' so I can output price label instead of the price value. Not sure how approach this in codeigniter. Do I use join the then nested select?:
table 1
id | price_1 | price_2 | price_3
1 | 6 | 5 | 4
Table 2
id | label | value
1 | £6.50 | 6
2 | £2.50 | 5
3 | £4.00 | 4
Any pointers would be appreciated.
You can first make a select from table 1. Then:-
$tags = array();
foreach($record_from_table1 as $record)
{
$tags[] = $record['price1'];
$tags[] = $record['price2'];
$tags[] = $record['price3'];
}
Then make array_unique($tags)
Make select query from table 2 and get corresponding label values and echo them.
thanks for pointers, but did it this way, based on Codeigniter Join with Multiple Conditions
$this->db->select('p1.label as pa_1, p2.label as pa_2, p3.label as pa_3, p4.label as pa_4, p5.label as pa_5');
$this->db->from('table1');
$this->db->join('table2 as p1', 'p1.value = price_1', 'left');
$this->db->join('table2 as p2', 'p2.value = price_2', 'left');
$this->db->join('table2 as p3', 'p3.value = price_3', 'left');
$query = $this->db->get();
Thanks, Dan

SQL query to remove certain text from each field in a specific column?

I recently recoded one of my sites, and the database structure is a little bit different.
I'm trying to convert the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434.jpg |
*----*----------------------------*
| 2 | 1288044935741310352357.rar |
*----*----------------------------*
Into the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434 |
*----*----------------------------*
| 2 | 1288044935741310352357 |
*----*----------------------------*
I know that I could do a foreach loop with PHP, and explode the file extension off the end, and update each row that way, but that seems like way too many queries for the task.
Is there any SQL query that I could run that would allow me to remove the file exentision from each field in the file_name column?
You can use the REPLACE() function in native MySQL to do a simple string replacement.
UPDATE tbl SET file_name = REPLACE(file_name, '.jpg', '');
UPDATE tbl SET file_name = REPLACE(file_name, '.rar', '');
This should work:
UPDATE MyTable
SET file_name = SUBSTRING(file_name,1, CHAR_LENGTH(file_name)-4)
This will strip off the final extension, if any, from file_name each time it is run. It is agnostic with respect to extension (so you can have ".foo" some day) and won't harm extensionless records.
UPDATE tbl
SET file_name = TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(file_name, '.', -1) FROM file_name);
You can use SUBSTRING_INDEX function
SUBSTRING_INDEX(str,delim,count)
Where str is the string, delim is the delimiter (from which you want a substring to the left or right of), and count specifies which delimiter (in the event there are multiple occurrences of the delimiter in the string)
Example:
UPDATE table SET file_name = SUBSTRING_INDEX(file_name , '.' , 1);