SQL search query not working when i set the ORDER DESC - sql-order-by

I have some customer info results displayed in a table. They are in ascending order so i have to scroll down to the bottom to get to the last one that registered. Or I can type the name, ID, or phone number to search for it. Everything works fine. Now i tried to change the order so i have the last one on the top...I placed ORDER BY id DESC right after WHERE 1 in the first line of the code...when i do that I get the desired order but the search stops working-syntax error. How can i change the order and still have the search query working. Im a PHP rookie.
The PHP Code
<?php
$query = "SELECT * FROM table_kontaktne_informacie WHERE 1";
if($meno_a_priezvisko!=""){ $query.=" AND meno_a_priezvisko LIKE '%".$meno_a_priezvisko."%' COLLATE 'utf8_general_ci' ";}
if($nazov_firmy!=""){ $query.=" AND nazov_firmy LIKE '%".$nazov_firmy."%' COLLATE 'utf8_general_ci' ";}
if($ico_firmy!=""){ $query.=" AND ico_firmy LIKE '%".$ico_firmy."%' ";}
if($telefon!=""){ $query.=" AND telefon LIKE '%".$telefon."%' ";}
if($referencny_kod!=""){ $query.=" AND referencny_kod LIKE '%".$referencny_kod."%' COLLATE 'utf8_general_ci' ";
;}
mysql_query("SET CHARACTER SET utf8");
$result = mysql_query($query,$db) or die (mysql_error($db));
while($line = mysql_fetch_array($result)) {
echo '<tr class="databaza_uzivatelov_riadok" onclick="window.location=\'formular_databaza_kontaktov_kontakt.php?id='.$line["id"].'\'" >';
echo '<td align="center">'.$pocet.'</td>';
echo "<td>".$line["meno_a_priezvisko"]."</td>";
echo "<td style='font-size:12px; padding-top:8px;'>".$line["nazov_firmy"]."</td>";
echo "<td>".$line["ico_firmy"]."</td>";
echo "<td>".$line["telefon"]."</td>";
echo "<td>".$line["email"]."</td>";
echo "<td><a class='ref' href=\"http://www.opravit.sk/ref.php?=".$line["referencny_kod"]. "\">".$line["referencny_kod"]."</a></td>";
echo "<td>".$line["kredit"]."</td>";
echo "</tr>";
$pocet ++;}
?>

Put the ORDER BY id DESC at the very last in your query.
...
if($referencny_kod!=""){ $query.=" AND referencny_kod LIKE '%".$referencny_kod."%' COLLATE 'utf8_general_ci' ";}
$query .= " ORDER BY id DESC";
mysql_query("SET CHARACTER SET utf8");
....

You have to add the ORDER BY at the end of the query.
Syntax definition from w3cschools.org
SQL ORDER BY Syntax
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;
And here the code that should fix your problem:
<?php
$query = "SELECT * FROM table_kontaktne_informacie WHERE 1";
if($meno_a_priezvisko!=""){ $query.=" AND meno_a_priezvisko LIKE '%".$meno_a_priezvisko."%' COLLATE 'utf8_general_ci' ";}
if($nazov_firmy!=""){ $query.=" AND nazov_firmy LIKE '%".$nazov_firmy."%' COLLATE 'utf8_general_ci' ";}
if($ico_firmy!=""){ $query.=" AND ico_firmy LIKE '%".$ico_firmy."%' ";}
if($telefon!=""){ $query.=" AND telefon LIKE '%".$telefon."%' ";}
if($referencny_kod!=""){ $query.=" AND referencny_kod LIKE '%".$referencny_kod."%' COLLATE 'utf8_general_ci' ";
$query.=" ORDER BY id DESC"
;}

Related

German characters en-/decoding issue

I have a perl script. The simplified version looks like this:
my $sel = "SELECT DBMS_METADATA.GET_DDL($type, '$name', '$owner') FROM DUAL";
my $sth = $dbh->prepare( $sel ) or die "Can't prepare statement: $DBI::errstr";
my $rc = $sth->execute or die "Can't execute statement: $DBI::errstr";
my $code = $sth->fetchrow();
$sql = "INSERT INTO MY_TABLE (CODE) VALUES (?)";
$stmt = $dbh->prepare($sql);
$stmt->execute($code);
So, the script simpy get a CLOB text, save it in a $code variable and insert it to a table.
The command SELECT * FROM NLS_DATABASE_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'; returns WE8MSWIN1252.
My problem is, that in the $code variable occur German characters. After executing the INSERT to DB the encoding is wrong. The geman special characters(umlauts) are displayed not correctly. guess_encoding($code); returns Encode::XS=SCALAR(0x...).
How can I decode and encode the $code variable in a proper way? How can I check what the guess_encoding returns? As already mentioned, the 'CODE' field is of type CLOB.

Bash Heredoc format adding a new line at the end of );

I'm trying to create a bash script to create automated sql statements to run them in DB without the effort of manually modify the .sql script and avoid human error, there is an issue when it generates the output files using heredoc format, is adding a new line at the end of the bash script where sql statement end in );
I know this can be easy thing like scape this characters but I tried to scape them with backslash and is not working, here is my example:
cat <<EOF >> $updateTabletmp
INSERT INTO ${table}_${currentTimeStamp}
SELECT * FROM ${table} WHERE field_1= ${count} AND field_2 = (SELECT field_2
FROM bartable WHERE field_2 = ${store});
EOF
This is the current output:
INSERT INTO foo_123419294
SELECT * FROM PHYPIOEE WHERE field_1 = 2177 AND field_2= (SELECT field_2
FROM bartable WHERE field_2 = 8788
);
As you can see of some reason ); is moved as a new line, the expected output will be something like this:
INSERT INTO foo_123419294
SELECT * FROM PHYPIOEE WHERE field_1 = 2177 AND field_2= (SELECT field_2
FROM bartable WHERE field_2 = 8788);
Thanks
Just tested your script and it does not add any unexpected new line/s
#!/bin/sh
out=out.txt
table=table
currentTimeStamp=12345678
count=123
store=asdf
cat <<EOF >> $out
INSERT INTO ${table}_${currentTimeStamp}
SELECT * FROM ${table} WHERE field_1= ${count} AND field_2 = (SELECT field_2
FROM bartable WHERE field_2 = ${store});
EOF
and the result is:
INSERT INTO table_12345678
SELECT * FROM table WHERE field_1= 123 AND field_2 = (SELECT field_2
FROM bartable WHERE field_2 = asdf);
So the reason can be only one: your ${store} variable contains new line.
And that's the answer.

CodeIgniter parameterize integer and string

$code = Array(1,2,3,4)
$sql = "SELECT * FROM Table1 WHERE Field1 IN (?)";
$query = $this->db->query($sql, array($code));
$this->db->last_query() will show
"SELECT * FROM Table1 WHERE Field1 IN ('1,2,3,4')"
How can I remove the single quote in the IN condition?
Even if the $code is array of strings, example
$code = Array('This one', 'Next code', 'And this')
the statement will be:
"SELECT * FROM Table1 WHERE Field1 IN ('This one, Next Code, And This')"
Am I missing something ?
TIA.
You can use this simple and alternate way
$this->db->where_in('Field1',$code);
$this->db->get('Table1');
From codeigniter active record manual
$this->db->where() accepts an optional third parameter. If you set it
to FALSE, CodeIgniter will not try to protect your field or table
names with backticks.
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
So, put a 3rd parameter on a where clause with FALSE
Then your query should be
$this->db->select('*')
->where('Field1 IN('.$code.'),NULL,FALSE)
->get('Table1');

CodeIgniter and csv_from_result

I have getting data from a database and using
$query = $this->db->query("SELECT * FROM mytable");
echo $this->dbutil->csv_from_result($query);
however I want to change the name of my headers for the CSV for first_name is First Name...how would I go about doing that?
Thanks,
J
Try renaming the columns returned by the sql query:
$query = $this->db->query("
SELECT
first_name as 'First Name', last_name as 'Last Name'
FROM mytable
");
The downside is that you will have to list the columns instead of a simple *.

iplementing sql query in codeigniter

SELECT * FROM abc
WHERE xyz LIKE $x OR xyz LIKE $y OR xyz LIKE $z
ORDER BY ((xyz LIKE $x) + (xyz LIKE $y) + (xyz LIKE $z)) DESC
I am able to write the query for pretty much ordey by asd desc but how to write this complex query in codeigniter?
You can write it in plain sql like you have it and execute it with the db->query method.
$sql = 'SELECT * FROM abc
WHERE xyz LIKE ? OR xyz LIKE ? OR xyz LIKE ?
ORDER BY ((xyz LIKE ?) + (xyz LIKE ?) + (xyz LIKE ?)) DESC'
$this->db->query($sql, array($x, $y, $z, $x, $y, $z));
http://codeigniter.com/user_guide/database/queries.html query bindings explains the ?
Maybe you should check ActiveRecord:
$this->db->
from("abc")->
or_like("xyz",$x)->
or_like(...)->
order_by(...);
$result = $this->db->result_array();

Resources