I have this sql statement for my search function.
$a_search = "$a%";
$sql = "SELECT a.*, u.*
FROM articles AS a
LEFT JOIN users AS u
ON a.written_by = u.username
WHERE a.written_by OR a.title LIKE ? // want to search for both
ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$a_search);
$stmt->execute();
$result = $stmt->get_result();
// more code ...
Works fine except one thing. It searches the articles ONLY where the a.title match. But I also want to search by the author and that's why I added a.written_by. However it still only searches for the a.title. So my question is how can I search for both at the same time?
What you wrote has no condition on a.written_by
you have to do something like
$a_search = "$a%";
$sql = "SELECT a.*, u.*
FROM articles AS a
LEFT JOIN users AS u
ON a.written_by = u.username
WHERE a.written_by LIKE ? OR a.title LIKE ? // want to search for both
ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param($a_search,$a_search);
$stmt->execute();
$result = $stmt->get_result();
// more code ...
This will send the result where a.written_by LIKE $a_search or a.title LIKE $a_search
you cannot give a common or and....gotta mention it in each case...for e.g.
$a_search = "$a%";
$sql = "SELECT a.*, u.*
FROM articles AS a
LEFT JOIN users AS u
ON a.written_by = u.username
WHERE a.written_by ='cat' OR a.title LIKE 'dog' ? // want to search
ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$a_search);
$stmt->execute();
$result = $stmt->get_result();
// more code ..
Related
I want to view data from mysql in codeigniter based on user who is logged in
but I got an error "A Database Error Occurred". I think I wrote the wrong code
t.USER = $this->session->userdata('user_id');
Here's the code:
function get_rekomen()
{
$query = $this->db->query("SELECT
c.*,
t.produk_id,
t.id_transdet,
t.kategori_id,
t.total_qty,
t.USER
FROM
transaksi_detail AS t
LEFT JOIN
(
SELECT
g.id_produk,
p.slug_produk,
p.foto,
p.foto_type,
p.harga_diskon,
p.diskon,
p.harga_normal,
p.judul_produk,
g.kat_id,
k.judul_kategori
FROM
(
SELECT
MAX(m.id_produk) AS id_produk,
m.kat_id
FROM
produk AS m
GROUP BY
m.kat_id
)
AS g
INNER JOIN
produk AS p
ON p.id_produk = g.id_produk
LEFT JOIN
kategori AS k
ON k.id_kategori = g.kat_id
)
AS c
ON c.kat_id = t.kategori_id
WHERE
t.USER = $ this -> session -> userdata('user_id');
<<// i think here's the problem
ORDER BY
total_qty DESC limit 1")->result();
return $query;
}
and the question is what is the correct code?
Here's one solution, but first make sure on your controller the $this->load->library('session'); is loaded or you can just add in on autoload.php.
Also you must add parameter to your model that will handle the user_id in session, so for example here's your model looks like:
function get_rekomen($user_id) { ...your query here... }
Then on condition using the user_id will be
t.USER = $user_id;
So on your controller, you can call your model like:
$user_id = $this->session->userdata('user_id');
$this->ModelClass->get_rekomen($user_id);
Additional: On your login phase, if the user success from logging in, the you must set the user data on session such as this $this->session->set_userdata('user_data', $session_data);
Hope this helps!
Maybe you can use this. You need to define $user_id first before adding them to WHERE statement...
$user_id = $this->session->userdata('user_id');
$sql = "SELECT c.*, t.produk_id, t.id_transdet, t.kategori_id, t.total_qty, t.USER
FROM transaksi_detail AS t
LEFT JOIN(SELECT g.id_produk, p.slug_produk, p.foto, p.foto_type, p.harga_diskon, p.diskon, p.harga_normal, p.judul_produk, g.kat_id, k.judul_kategori
FROM(SELECT MAX(m.id_produk) AS id_produk, m.kat_id
FROM produk AS m
GROUP BY m.kat_id)
AS g
INNER JOIN produk AS p ON p.id_produk = g.id_produk
LEFT JOIN kategori AS k ON k.id_kategori = g.kat_id)
AS c ON c.kat_id = t.kategori_id
WHERE t.USER = '$user_id'
ORDER BY total_qty DESC limit 1";
$query = $this->db->query($sql);
return $query->result();
Hope this can help you...
I use code below to get data from database
if( !empty( $books_ids ) )
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";
$stmt = $conn->prepare($query);
foreach ($books_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
$stmt->execute();
$results = $stmt->fetchAll();
}
and as I use $book id for this purpose, I would like to add some parameter in result to show that, for example, param = "book" for every row. Is there any way to do that?
Just pass it the string and alias it as a column. Though since you know the value passed in in code and display the values though code...... I'm not sure why you need this... as the value is available to you in the code when being displayed.
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'". $param."' as forEveryRow
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";
I have this query here
$rs = mysql_query("select Username.users,phone.users,user_id.coupon,points.coupon,time.coupon from users LEFT JOIN coupon on Username.users = coupon.user_id where coupon.user_id like '%$search%' or coupon.time like '%$search%' order by $sort $order limit $offset,$rows");
Where
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'time';
Am i doing any error here?
I don't get any result,
please help me with this.
Thanks..
You are selecting columnname.tablename instead of tablename.columnname. So instead of Username.users use users.Username and all respective.
select users.Username --<-- here
,users.phone ,coupon.user_id. ,coupon.points ,coupon.time
from users LEFT JOIN coupon
on users.Username = coupon.user_id --<-- also here
where ...
Also, you can use alias to reduce your query length and time of writing query and for more simplicity like this:
select u.Username --<-- here
,u.phone ,c.user_id. ,c.points ,c.time
from users u LEFT JOIN coupon c
on u.Username = c.user_id --<-- also here
where ...
Try to write the query the following way which may help:
$rs = mysql_query("select users.Username,users.phone,coupon.user_id,coupon.points,coupon.time from users LEFT JOIN coupon on users.Username = coupon.user_id
where coupon.user_id like '%$search%' or coupon.time like '%$search%' order by $sort $order limit $offset,$rows");
Just verify that users.Username is in fact the correct id to join on the coupon table. Shouldn't it be users.user_id? In which case it will be
$rs = mysql_query("select users.Username,users.phone,coupon.user_id,coupon.points,coupon.time from users LEFT JOIN coupon on users.user_id = coupon.user_id
where coupon.user_id like '%$search%' or coupon.time like '%$search%' order by $sort $order limit $offset,$rows");
more appropriate method,
as time is a type in Sql
select users.`Username`, users.`phone`, coupon.`user_id`, coupon.`points`,coupon.`time` from users
LEFT JOIN coupon
on users.`Username` = coupon.`user_id`
where coupon.`user_id` like '%$search%' or coupon.`time` like '%$search%'
How can I make my search form to only list results where hidden = '0'; + rest of the options ?
$stmt = $dbh->prepare("
SELECT *
FROM users u
LEFT JOIN menues m
ON u.user_id = m.restaurant_id
WHERE (restaurant LIKE CONCAT('%', :term, '%'))
OR city LIKE CONCAT('%', :term, '%')
");
$stmt->bindParam(":term", $term);
$stmt->execute();
Thanks in advance :)
Well, I hope I understand what you need:
$stmt = $dbh->prepare("
SELECT *
FROM users u
LEFT JOIN menues m
ON u.user_id = m.restaurant_id
WHERE (((restaurant LIKE CONCAT('%', :term, '%'))
OR city LIKE CONCAT('%', :term, '%'))
AND hidden = 0)
");
$stmt->bindParam(":term", $term);
$stmt->execute();
Can you not just add
AND hidden = '0'
to the end of your WHERE clause so your query ends
.
.
.
WHERE (restaurant LIKE ...
OR city LIKE ...)
AND hidden='0'
Incidentally is hidden really a character-based column? If not, you should be adding hidden=0 (without single quotes)
I want to write a mySQL query like the following in zend framework 2.
How to convert it in zend Db select convention?
SELECT profiles.*,
user.email,
user.first_name,
user.last_name,
portfilio_images.profileImage,
images.url AS imgurl
FROM profiles
INNER JOIN user ON user.user_id = profiles.ownerId
LEFT JOIN (
SELECT *
FROM portfilio_images
WHERE portfilio_images.profileImage = '1'
) as portfilio_images ON portfilio_images.profileId = profiles.id
LEFT JOIN images ON images.id = portfilio_images.imageId
WHERE profiles.ownerId != '4' AND (profiles.name LIKE '%a%' OR user.first_name LIKE '%a%' OR user.last_name LIKE '%a%')
GROUP BY user.user_id
You can also use Zend\Db\Sql\Select that allows you to build complex queries programatically. See the documentation here:
http://zf2.readthedocs.org/en/release-2.1.1/modules/zend.db.sql.html#zend-db-sql-select
You could always just perform a raw query:
$sql = "SELECT * FROM test";
$statement = $abAdapter->query($sql);
$result = $statement->execute();
$resultSet = new ResultSet;
$resultSet->initialize($result);
return $resultSet;
Or if you want to add some parameters
$sql = "SELECT * FROM test where col = ?";
$statement = $dbAdapter->query($sql);
$result = $statement->execute(array(99));
$resultSet = new ResultSet;
$resultSet->initialize($result);
return $resultSet;