Assistance required converting MySQL function to PDO - mysql

I'm currently converting MySQL to PDO, I'm unsure if I wrote this function correctly,I'm also unsure of how to use sqlfiddle, so I resort to Stackoverflow.
If correct, anything to better the current code?
MySQL example :
PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
$update = mysql_real_escape_string($update);
$time = time();
$_iP = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("SELECT post_iD,message FROM `Posts` WHERE uid_fk='$_iD' ORDER by post_iD DESC LIMIT 1") or die(mysql_error());
$result = mysql_fetch_array($query);
if ($update!=$result['message']) {
$uploads_array = explode(',',$uploads);
$uploads = implode(',',array_unique($uploads_array));
$query = mysql_query("INSERT INTO `Posts` (message, uid_fk, _iP,created,uploads) VALUES (N'$update', '$_iD', '$_iP','$time','$uploads')") or die(mysql_error());
$newquery = mysql_query("SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername FROM Posts M, users U where M.uid_fk=U._iD and M.uid_fk='$_iD' order by M.post_iD desc limit 1 ");
$result = mysql_fetch_array($newquery);
return $result;
} else {
return false;
}
}
PDO Example:
PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
$sth = $this->db->prepare("SELECT post_iD,message FROM `Posts` WHERE uid_fk = :id ORDER by post_iD DESC LIMIT 1")
$sth->execute(array('id' => $_iD));
$result = $sth->FetchAll(PDO::FETCH_ASSOC);
if ( $update!=$result['message'] ){
$uploads_array = explode(',',$uploads);
$uploads = implode(',',array_unique($uploads_array));
$sth = $this->db->prepare("INSERT INTO Posts (message, uid_fk, _iP,created,uploads) VALUES ( :update, :id, :ip, :time, :uploads)")
$sth->bindValue(':update', $update);
$sth->bindValue(':id', $_iD);
$sth->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
$sth->bindValue(':time', time());
$sth->bindValue(':uploads', $uploads);
$sth->execute()
$sth = $this->db->prepare("
SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername
FROM Posts M, users U
WHERE M.uid_fk=U._iD
AND M.uid_fk = :id
ORDER by M.post_iD DESC LIMIT 1 ");
$sth->execute(array(':id' => $_iD));
$result = $sth->FetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return false;
}
}

Related

Laravel Eloquent left join query

I have like this query which work in plain sql:
SELECT users.id, users.name, roles.name
FROM users
LEFT JOIN model_has_roles ON model_has_roles.model_id = users.id
LEFT JOIN roles ON roles.id = model_has_roles.role_id
ORDER BY roles.name ASC
Using laravel I tried like this but it's doesn't work:
$user = $request->user();
$role = (array) $request->get('role', []);
$order = (array) $request->get('order');
$perPage = $request->get('perPage') ?? 10;
$users = User::where('id', '!=', $user->id);
if(count($role)) {
if (($key = array_search('admin', $role)) !== false) {
unset($role[$key]);
}
$users = $users->whereHas('roles', function ($query) use($role) {
return $query->whereIn('name', $role);
});
} else {
$users = $users->whereHas('roles', function ($query) {
return $query->whereIn('name', ['farmer', 'specialist', 'company']);
});
}
if(count($order) && isset($order['field'])) {
$orderType = $order['type'] ?? 'ASC';
if($order['field'] == 'role') {
$users = $users->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name', $orderType);
} else {
$users = $users->orderBy($order['field'], $orderType);
}
}
$users = $users->paginate($perPage);
Error message:
`"message": "SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select count(*) as aggregate from `users` left join `model_has_roles` on` `model_has_roles`.`model_id` = `users`.`id` left join `roles` on `roles`.`id` = `model_has_roles`.`role_id` where `id` != 3 and exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_id` and `model_has_roles`.`model_type` = App\\Models\\User and `name` in (specialist, company)))",
Because your both models have id and after sql execute the query id column will be ambiguous so this will help you:
$users = User::where('id', '!=', $user->id);
change to
$users = User::where('users.id', '!=', $user->id);
Then try:
$users = $users->select(['users.id', 'users.name', 'roles.name'])
->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name', 'ASC');

Mysql Query with SUM and WHERE does not work

include 'conn.php';
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'saleid';
$order = isset($_POST['order']) ? strval($_POST['order']) : 'desc';
$orderno = isset($_POST['orderno']) ? mysql_real_escape_string($_POST['orderno']) : '';
$offset = ($page-1)*$rows;
$result = array();
$where = "orderno like '$orderno%'";
$rs = mysql_query("select count(*) from tblsales where " . $where);
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$rs = mysql_query("select *, sum(price+shipping+paypalfee+storefee) as totalcost from tblsales group by orderno where " . $where . " order by $sort $order limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
Could you please change this query so that it returns all records in table while using WHERE clause so that I could search a particular record if needed. At the moment it does not return anything:
select *, sum(price+shipping+paypalfee+storefee) as totalcost
from tblsales
group by orderno
where " . $where . "
order by $sort $order
limit $offset,$rows
Try this
select *,sum(totalcost)
FROM (select *, price+shipping+paypalfee+storefee as totalcost from tblsales) x
group by orderno
where " . $where . "
order by $sort $order
limit $offset,$rows

Add many-to-many select into existing query

I have a query set up to return comments given from one user to another.
Now we want to allow the ability to rate these comments.
I've added a new table that has 3 fields: comment_id, user_id, and score.
How can I grab an array of {user_id,score} for any comment fetched?
Will I need to loop through the comments after they are fetched and run a second query? This approach could result in adding several extra queries.
Can it be done with a single query?
Here's the function I have now:
function getAllComments($args) {
if(empty($_SESSION['user']['id'])) return false;
$limit = 5;
if(isset($args['limit'])) $limit = $args['limit'];
$page = 1;
if(isset($args['page'])) $page = $args['page'];
$data = array();
$offset = ($page-1)*$limit;
$sql = "SELECT c.*,CONCAT(u1.firstName,' ',u1.lastName) AS owner,u1.title AS ownerTitle,CONCAT_WS(' ',u2.firstName,u2.lastName) AS senderName,u2.title AS senderTitle,a.name AS actionName,a.behavior
FROM comment AS c
JOIN user AS u1 ON c.recipient = u1.id
JOIN user AS u2 ON c.sender = u2.id
JOIN action AS a ON c.action = a.id
WHERE c.type=1";
if(isset($args['location'])) $sql .= " AND u1.location=?";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT ?";
$sql .= " OFFSET ?";
try {
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$n = 1;
//THESE MUST STAY IN THE SAME ORDER TO MATCH THE ? PLACEHOLDERS
if(isset($args['location'])) $stmt->bindValue(($n++), $args['location'], PDO::PARAM_INT);
$stmt->bindValue(($n++), $limit, PDO::PARAM_INT);
$stmt->bindValue(($n++), $offset, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = array();
if($result !== false) {
while($row = $stmt->fetch()) {
$rows[] = $row;
}
$data['comments'] = $rows;
return $data;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
}
If you for example wanted all {comment_id, user_id, score} associated with the comments of user 5, your query would involve an INNER JOIN and look something like:
SELECT s.comment_id, s.user_id, s.score FROM CommentScore s
INNER JOIN Comment c
ON c.comment_id = s.comment_id
WHERE c.user_id = 5

MySQL order by $variable

I am trying to think of a way to order the results from the highest number to the lowest one.
The problem here is that those numbers will be from a different table and I am not sure how I should do it.
Please check out below.. *
Thanks!
*Edit:
I know that I suck at coding but still :)
What I need is instead of ORDER BY id to be Order by $results (highest number to lower)
Current Code I am using:
$query = "SELECT * FROM tablea WHERE id > 1 AND status = '1' ORDER BY id ASC;";
$result = #mysql_query($query);
for ($i=0; $i < #mysql_num_rows ($result); $i++) {
$row = #mysql_fetch_array($result);
$total = $total + 1;
$results = '';
$noinv = '';
$query2 = "SELECT SUM(number) FROM tableb WHERE id = '$row[id]' AND cur = '1' AND type = '1' AND pos = '1';";
$result2 = #mysql_query($query2);
$row2 = #mysql_fetch_array($result2);
if ($row2['SUM(number)'] == '') {
$row2['SUM(number)'] = '0.00';
}
$query3 = "SELECT SUM(number) FROM tableb WHERE id = '$row[id]' AND cur = '1' AND type = '1' AND pos = '2';";
$result3 = #mysql_query($query3);
$row3 = #mysql_fetch_array($result3);
if ($row3['SUM(number)'] == '') {
$row3['SUM(number)'] = '0.00';
}
$results = $row3['SUM(number)'] - $row2['SUM(number)'];
print $row['id'].' '.$row['status'].' '.$results;
}
your question is unclear, but try to give you general answer
select A.column1,A.column2,A.column3,count(B.*) total
from table A, table B
where A.Id=B.Id
group by A.Id
order by total desc

How to get PDO to select from more than one table

Here is my code:
$sql= ("SELECT R.cr_id,R.time,R.reply,U.user_id,U.user_name FROM tb_user U, conversation_reply R WHERE R.user_id_fk=U.user_id and R.c_id_fk='$c_id' ORDER BY R.cr_id ASC LIMIT 20");
$stmt = $conn->prepare($sql);
$stmt->execute();
$row=$stmt->fetchAll();
foreach ($row as $laww) {
echo $laww['$user_name'].":". $laww['reply']. "<br>";
}
}////END
I get only the result from $laww['reply'] but not $laww['$user_name']
Can anyone helpe me ?