i have mysql table:
id | nameEng | NameRus
1 | Moscow | Москва
2 | London | Лондон
What i want is:
$result = array (
1 => array (id => 1, Name => "Москва"),
2 => array (id => 1, Name => "Moscow"),
3 => array (id => 2, Name => "London"),
4 => array (id => 2, Name => "Лондон")
)
Here is my query:
mysql_query("SELECT id, nameRus FROM citynames WHERE nameRus LIKE '%".$_GET['chars']."%'
UNION ALL
SELECT id, nameEng FROM citynames WHERE nameEng LIKE '%".$_GET['chars']."%' ORDER BY nameEng LIMIT 0, 10"
Query working but i want to optimize this query
$l = "like '%". $_GET['chars'] ."%'";
$sql = "(select `id` as `id`, `nameEng` as `name` from `citynames `) union (select `id` as `id`, `NameRus` as `name` from `citynames `) where `name` $l order by `id`;";
Related
Before you misread the title... I'm not asking how to echo the number of rows, I'm simply looking to find the position that the row is in.
Let's say we have five total rows:
+---------------------+
| Post ID | Author |
+---------------------+
| 463 | Me |
| 477 | Me |
| 718 | Me |
| 883 | Me |
| 276 | Me |
+---------------------+
Now I'd like to get the position of the row that contains the post ID of 718. From looking at the data, we can visually see that it is the third row in the data. How can I echo this in PHP?
when you fetch records, you may use a variable as position number.
#DB is a class connect to mysql database.
DB::init();
$sql = "SELECT * FROM RowNo ";
$stmt = DB::query( $sql );
$i = 1;
while( $rec1 = $stmt->fetch() ) {
echo "row $i : ";
print_r( $rec1 );
echo '<BR>'.PHP_EOL;
$i++;
};
result :
row 1 : Array ( [Post ID] => 8788277463 [Author] => Me )
row 2 : Array ( [Post ID] => 2894728477 [Author] => Me )
row 3 : Array ( [Post ID] => 3898994718 [Author] => Me )
row 4 : Array ( [Post ID] => 4891784883 [Author] => Me )
row 5 : Array ( [Post ID] => 1185819276 [Author] => Me )
You may use row_number :
#1. ORDER BY Post ID
SELECT * , row_number() over ( order by Post ID ) FROM RowNo order by Post ID asc
Post ID Author row_number() over ( order by `Post ID` )
1185819276 Me 1
2894728477 Me 2
3898994718 Me 3
4891784883 Me 4
8788277463 Me 5
#2. ORDER BY Post ID DESC
SELECT * , row_number() over ( order by Post ID desc ) FROM RowNo order by Post ID desc
Post ID Ascending 1 Author row_number() over ( order by `Post ID` desc )
8788277463 Me 1
4891784883 Me 2
3898994718 Me 3
2894728477 Me 4
1185819276 Me 5
#3. ORDER BY part of Post ID
SELECT * , substr(Post ID, 4, 2), row_number() over ( order by substr(Post ID, 4, 2) ) FROM RowNo order by substr(Post ID, 4, 2) asc
Post ID Author substr(`Post ID`, 4, 2) Ascending 1 row_number() over ( order by substr(`Post ID`, 4, 2) )
4891784883 Me 17 1
2894728477 Me 47 2
1185819276 Me 58 3
8788277463 Me 82 4
3898994718 Me 89 5
I have two table like this:
Product
id | title
-------------------------------
1 | Skirt
2 | Pants
Product_thumbnail
id | product_id | image
-------------------------------
1 | 1 | pant.jpg
2 | 1 | shoes.png
When I want to get product with the thumbnail, I query like this:
SELECT p.*, pt.image FROM product p
LEFT JOIN product_thumbnail pt ON pt.product_id = p.id;
The output I expected
[0]=> [
[id] => 1
[image] =>
[
[0] => pant.jpg
[1] => shoes.jpg
]
]
[1]=> [
[id] => 2
[image] => null
]
But the real output
[0]=> [
id => 1
image => pant.jpg
]
[1]=> [
id => 1
image => shoes.jpg
]
[2]=> [
id => 2
image => shoes.jpg
]
As you see, there is 2 element duplicate, so I need to merge it by hand, is there any way to achieve this more easy? Because my table have many tables relate together more than this, I'm using PHP, I use array_merge_recursive() to merge them but if do like that I get duplicate value in each field, like this:
[0]=> [
[id] =>
[
[0] => 1
[1] => 1
]
[image] =>
[
[0] => pant.jpg
[1] => shoes.jpg
]
]
It's not what I want, can anyone give me an idea?
Consider the following. The code could I'm sure be written more economically, but hopefully you get the idea...
<?php
/*
DROP TABLE IF EXISTS product;
CREATE TABLE product
(id SERIAL PRIMARY KEY
,title VARCHAR(12) NOT NULL UNIQUE
);
INSERT INTO product VALUES
(1,'Hat'),
(2,'Shoe');
DROP TABLE IF EXISTS product_thumbnail;
CREATE TABLE product_thumbnail
(id SERIAL PRIMARY KEY
,product_id INT NOT NULL
,image VARCHAR(12) NOT NULL UNIQUE
);
INSERT INTO product_thumbnail VALUES
(1,1,'sombrero.jpg'),
(2,1,'stetson.png');
SELECT p.id
, p.title
, t.image
FROM product p
LEFT
JOIN product_thumbnail t
ON t.product_id = p.id;
+----+-------+--------------+
| id | title | image |
+----+-------+--------------+
| 1 | Hat | sombrero.jpg |
| 1 | Hat | stetson.png |
| 2 | Shoe | NULL |
+----+-------+--------------+
*/
require('path/to/connection/stateme.nts');
$query = "
SELECT p.id
, p.title
, t.image
FROM product p
LEFT
JOIN product_thumbnail t
ON t.product_id = p.id;
";
$result = mysqli_query($db,$query);
$old_array = array();
while($row = mysqli_fetch_assoc($result)){
$old_array[] = $row;
}
$new_array = array();
foreach ($old_array as $row) {
$new_array[$row['id']]['title'] = $row['title'];
$new_array[$row['id']]['image'][] = $row['image'];
}
$new_array = array_values($new_array); // reindex
print_r($new_array);
?>
Outputs
Array
(
[0] => Array
(
[title] => Hat
[image] => Array
(
[0] => sombrero.jpg
[1] => stetson.png
)
)
[1] => Array
(
[title] => Shoe
[image] => Array
(
[0] =>
)
)
)
MySQL doesn't support arrays, but you can aggregate the data into a string:
SELECT p.*, GROUP_CONCAT(pt.image) as images
FROM product p LEFT JOIN
product_thumbnail pt
ON pt.product_id = p.id
GROUP BY p.id;
Note that aggregating only by the id and selecting p.* is allowed and even standard SQL -- assuming that id is a primary key or declared to be unique. This is the one situation when this syntax is permitted.
I have table:
+---------------+------------------------------+-----+------+
| id_order | id_product | qty | size |
+---------------+------------------------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2,PRD-0412-17-11 | 2,3 | M,S |
+---------------+------------------------------+-----+------+
I would like to have an output like this:
+---------------+---------------+-----+-------+
| id_order | id_product | qty | size |
+---------------+----------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2 | 2 | M |
| ORD-0413-17-1 | PRD-0412-17-11 | 3 | S |
+---------------+----------------+-----+------+
How I can do this?
Here's one way in which to build a normalized 'result' from your 'data'... I'm using a simple utility table of integers (0-9), but you could just use a bunch of UNIONs instead.
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id_order VARCHAR(20) NOT NULL
,id_product VARCHAR(255) NOT NULL
,qty VARCHAR(30) NOT NULL
,size VARCHAR(30) NOT NULL
);
INSERT INTO my_table VALUES
('ORD-0413-17-1','PRD-0408-17-2,PRD-0412-17-11','2,3','M,S');
DROP TABLE IF EXISTS ints;
CREATE TABLE ints(i INT NOT NULL PRIMARY KEY);
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
SELECT DISTINCT id_order
, SUBSTRING_INDEX(SUBSTRING_INDEX(id_product,',',i+1),',',-1) id_product
, SUBSTRING_INDEX(SUBSTRING_INDEX(qty,',',i+1),',',-1) qty
, SUBSTRING_INDEX(SUBSTRING_INDEX(size,',',i+1),',',-1) size
FROM my_table,ints;
id_order id_product qty size
ORD-0413-17-1 PRD-0408-17-2 2 M
ORD-0413-17-1 PRD-0412-17-11 3 S
in my case, am using method in class php, this is the method :
public function user_checkout($params){
$date = new DateTime(date('Y-m-d'));
$date->modify('+3 day');
$query = "SELECT * FROM cart WHERE id_session='".$params['id_user']."'";
$sql = $this->db->query($query);
$data1 = array();
$data2 = array();
$data3 = array();
while($result = $sql->fetch_assoc()){
$data1[] = $result['id_product'];
$data2[] = $result['qty'];
$data3[] = $result['size'];
}
$data_insert = array(
"id_order" => $params['id_order'],
"id_product" => implode(',', $data1),
"id_user" => $params['id_user'],
"qty" => implode(',', $data2),
"size" => implode(',', $data3),
"account_name" => $params['name_of_account'],
"account_number" => $params['no_rekening'],
"amount" => $params['amount'],
"total_price" => $params['total_price'],
"out_of_date" => $date->format('Y-m-d'),
"order_date" => date('Y-m-d')
);
$insert = "INSERT INTO `order_product`(`id_order`, `id_product`, `id_user`, `qty`,`size`, `account_name`, `account_number`, `amout`, `total_price`, `out_of_date`, `order_date`, `status`) VALUES ('".$data_insert['id_order']."','".$data_insert['id_product']."','".$data_insert['id_user']."','".$data_insert['qty']."','".$data_insert['size']."','".$data_insert['account_name']."','".$data_insert['account_number']."','".$data_insert['amount']."','".$data_insert['total_price']."','".$data_insert['out_of_date']."','".$data_insert['order_date']."',0)";
$sql_insert = $this->db->query($insert);
$delete = "DELETE FROM cart WHERE id_session = '".$params['id_user']."'";
$sql_delete = $this->db->query($delete);
return true;
}
I would like to use data from an array to add a column and make a join on a MySql table.
Let's say, on one hand, we have an array ($relevance):
$relevance = array(
array('product_id' => 1, 'relevance' => 2),
array('product_id' => 2, 'relevance' => 5),
array('product_id' => 3, 'relevance' => 1),
);
And on the other hand, we have this table (products):
product_id | product_name
--------------------------
1 | Product 1
2 | Product 2
3 | Product 3
Now, I want to select data from the products table and joining them with $relevance based on their product_id in order to get something like this:
product_id | product_name | relevance
---------------------------------------
1 | Product 1 | 2
2 | Product 2 | 5
3 | Product 3 | 1
In other words, how can I make a SELECT with LEFT JOIN using data from both the MySql database and an array which would "mean" something like this:
SELECT `p`.*, `{{$relevance}}`.* FROM `products` AS `p`
LEFT JOIN `{{$relevance}}`
ON p.product_id = {{$relevance}}.product_id
pure sql solution, not efficient though for big recordsets:
$relevances = array()
foreach ($relevance as $v){
$relevances[] = "SELECT {$v['product_id']} as product_id, {$v['relevance']} as relevance"
}
$sql = implode(' UNION ', $relevances);
$sql = "SELECT p.product_id, p.product_name, r.relevance
FROM products p
JOIN ($sql) r ON p.product_id=r.product_id";
Well, you can make another table relevance and then you could just use JOIN. Or you can use loop to get those data. Something like
$relevance = array(
array(1, 'relevance' => 2),
array(2, 'relevance' => 5),
array(3, 'relevance' => 1),
);
$q = mysql_query("SELECT * FROM products")
while($r = mysql_fetch_assoc($q))
{
$productRelevance = $relevance[$r['prod_id']-1];
}
Hoewever this code may fail if you delete some product and those ids wouldn' be in order, e.g.: 1,2,5,6,7,10. I recommend you to use another table.
i want to insert the values of two arrays into a table in a single query . Is it possible to do something like that.
table format
id | product_id | category_id | blog_id | updated_by | created_date
category _id
Array
(
[0] => 4
[1] => 15
[2] => 18
)
Product_id
Array
(
[0] => 2260
[1] => 1401
)
Blog id = mysql_insert_id();
result
id | product_id | category_id | blog_id | updated_by
1 2260 4 15 xyz
2 1401 15 15 xyz
3 null 18 15 xyz
Any suggestions for me also to improve the better insert query for this.
INSERT INTO `Table_Name` (`product_id`, `category_id`, `blog_id`, `updated_by`) VALUES (2260, 4, 15, 'xyz'), (1401, 15, 15, 'xyz'), (, 18, 15, 'xyz');
I assumed that id column is an auto incremented one.
You can insert multiple rows at one go in the same query that you are using now. Just add a comma, and put in more values:
Insert into myTable values ('field1-var1','field2-var2'), ('field1-var2','field2-var2') ..
$combain = array_merge($cat , $proid);
for($i = 0; $i <count($combain); $i++ )
{
if(isset($proid[$i])) {
$product_id = $proid[$i];
}
else{
$product_id = "''";
}
if(isset($cat[$i])){
$category_id = $cat[$i];
}
else{
$category_id = "''";
}
if(!empty($cat[$i]) || !empty($proid[$i])) {
#$values[] ="('',". $blogid.",".$category_id.",".$product_id.","."'".$updated_by."'".",now())";
}
}
$query = $this->db->query("insert into blog_details (id , blog_id , cat_id, pro_id, updated_by , created_date) values" . implode(',', $values));