Illuminate \ Database \ QueryException (HY093) SQLSTATE[HY093]: Invalid parameter number - sql

I am trying to select the user_id of all posts whos id is the current index in the while loop and whose vote is 1 and turn it into a numerical array .
But,it keeps giving me this error:
Illuminate \ Database \ QueryException (HY093)
SQLSTATE[HY093]: Invalid parameter number (SQL: select `user_id` from `laravellikecomment_likes` where (`item_id` = 1 and `vote` = ?))
I dunno what to do now.Here is my code(part of it):
$db='laravellikecomment_likes';
$allposts= DB::table($db)->where('vote','!=',0)->get()->pluck('user_id');
$allposts = $allposts->toArray();
$tn=count($allposts);
$ai=0;
$user=Auth::id();
while ($ai <= $tn) {
$recclist=array();
$current=array_keys($allposts,$ai);
$id=1;
$wl=DB::table($db)->where(function ($query) use ($current, $id) {
$query->where('item_id', '=', $current);
$query->where('vote','=',$id);
})->pluck('user_id');

The error thrown has to do with your query
$wl=DB::table($db)->where(function ($query) use ($current, $id) {
$query->where('item_id', '=', $current); # This line is the culprit
$query->where('vote','=',$id);
})->pluck('user_id');
The error thrown, SQLSTATE[HY093]: Invalid Parameter number hints a parameter is wrong. In this case, you're trying to use an array where the Query Builder expects an integer or a string.
If you want to use an array, use whereIn instead of where, like so:
$wl=DB::table($db)->where(function ($query) use ($current, $id) {
$query->whereIn('item_id', $current); # Use whereIn to deal with arrays
$query->where('vote', '=', $id);
})->pluck('user_id');

Related

Remove bracket and quotations in JSON_AGG (Aggregate Functions)

public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
JSON_AGG(drug_dosage) AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
return response()->json([
'all_drugs'=>$all_drugs,
]);
}
I am using JSON_AGG to retrieve multiple lines of drug_dosage and combine them into one, but I am getting a bracket and quotation in my output, how do I take it out?
UPDATE:
I am getting errors in the examples because I am trying solutions using str_replace and preg_replace. my problem is that the target is in an SQL statement so I am suspecting that has something to do with the error since there is other data in the result
Error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
{"drug_code":"CFZU",
"drug_name":"Cefazolin",
"dosage_list":"[\"<=4 mg\/L\", \"<=3 mg\/L\"]"},
{"drug_code":"TZPD","drug_name":"Pip\/Tazobactam",
"dosage_list":"[\"Pip\/Tazobactam\"]"}
You can try string_agg instead JSON_AGG
public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
string_agg(drug_dosage, ', ') AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
return response()->json([
'all_drugs'=>$all_drugs,
]);
}
Because: JSON_AGG returns JSON ARRAY as STRING. After that you returned json encoded result from controller. This adds unwanted characters for make valid json encoding. (nested quotes must be escaped).
So;
Before sending result, you must json_decode for each record's drug_dosage field.
Example code:
public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
string_agg(drug_dosage, ', ') AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
foreach($all_drugs as $drug){
//decode postgresql 'json array like string presentation' to array.
$decoded = json_decode($drug->drug_dosage);
// if you want to remove null/empty values use array_filter
$filtered = array_filter($decoded); // default behavior removes falsy values.
// use same field to hold wanted, structured values
$drug->drug_dosage = $filtered;
}
// And return as json response like before.
return response()->json([
'all_drugs'=>$all_drugs,
]);
}

Getting Trying to get property * of non-object when using get_results in WordPress

I have two tables that have a one-to-one relationship. one of them is wp_posts and wp_books Now I want to get post that related to specif book with this code:
function column_default($item, $column_name) {
global $wpdb;
switch ($column_name) {
case 'post':
$post_query = "SELECT * FROM $wpdb->posts WHERE id = {$item->post_id}
AND post_type='books' LIMIT 1 ";
$post = $wpdb->get_results($post_query, OBJECT);
return $post->post_title;
default:
return $item;
}
}
But I get this error:
Trying to get property 'post_title' of non-object
What's wrong? How can I fix this?
The problem is that get_results actually returns an array (see https://developer.wordpress.org/reference/classes/wpdb/get_results/) therefore you are trying to read 'post_title' from an array which doesn't have that property and in fact it is an array, not an object.
You should use https://developer.wordpress.org/reference/classes/wpdb/#select-a-row "get_row" for that

Rewriting SQL query in Laravel but getting error BadMethodCallException: Call to undefined method

I'm trying to do this query in Laravel.
SELECT DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID
FROM curriculum
LEFT JOIN transcript
ON curriculum.Course_Code = transcript.Course_Code AND transcript.CWID = "C38475920";
Except I'm no longer using the static CWID ->"C38475920". This is what I have:
public function getProgress($id){
return DB::table('curriculum')
->select('curriculum.Course_Code','transcript.Course_Comp', 'transcript.Term_Completed', 'transcript.Course_Grade')
->distinct('curriculum.Course_Code')
->leftJoin('transcript', 'curriculum.Course_Code','=','transcript.Course_Code')
->on('CWID', '=', $id)
->get();
}
The function gives this error BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::on() in file
Do I have to add something to my model to use ON?
If you would like to use a "where" style clause on your joins, you may use the where methods on a join. Instead of comparing two columns, these methods will compare the column against a value.
The selectRaw method can be used in place of select(DB::raw(...)). This method accepts an optional array of bindings as its second argument.
DB::table('curriculum')
->selectRaw('DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID')
->leftJoin('transcript', function ($leftJoin) use ($id) {
$leftJoin->on('curriculum.Course_Code', '=', 'transcript.Course_Code')
->where('transcript.CWID', '=', $id);
})
->get();

laravel simple query builder (join & where case)

i have 2 table (product & type)
produk table
-id
-kode_produk
-nama_produk
-id_jenis_produk
and
jenis table
- id
- jenis_item
i wanna access database jenis_item from jenis tablewith query builder
so far i already try
$selectProduk = DB::table('produk')->where('id', $id)->join('jenis', 'produk.id_jenis_produk', '=', 'jenis.id')->first();
and something like this
$selectProduk = DB::table('produk')
->join('jenis', function($join) {
$join->on('produk.id_jenis_item', '=', 'jenis.id')
->where('produk.id', $id); // line 86 (error)
})->first();
but still failed with message error from laravel logs
exception 'ErrorException' with message 'Undefined variable: id' in C:\xampp\htdocs\itklan\app\controllers\ProdukController.php:86
where i'm missing?
#Thomas Kim
i get another error
exception 'ErrorException' with message 'Missing argument 3 for Illuminate\Database\Query\JoinClause::where(), called in C:\xampp\htdocs\itklan\app\controllers\ProdukController.php on line 86 and defined' in C:\xampp\htdocs\itklan\vendor\laravel\framework\src\Illuminate\Database\Query\JoinClause.php:87
line 87 :
$selectProduk = DB::table('produk')
->join('jenis', function($join) use($id) {
$join->on('produk.id_jenis_item', '=', 'jenis.id')
->where('produk.id', $id);
})->first(); //line 87
This is how PHP closures work. In order to use $id, the closure must inherit the variable from the parent scope by using the use keyword. For example:
$selectProduk = DB::table('produk')
->join('jenis', function($join) use($id) { // Check this line
$join->on('produk.id_jenis_item', '=', 'jenis.id')
->where('produk.id', '=', $id);
})->first();
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Source: http://php.net/manual/en/functions.anonymous.php
Edit:
Also, looks like with Laravel's JoinClause, you need to be specific about your operators. Normally, you can do this:
->where('produk.id', $id);
And Laravel adds an equal operator for you. However, for join clauses, this will not work. You need to specify the operator.
->where('produk.id', '=', $id);

pdo is not returning an output. Fatal error: Call to a member function fetch() on a non-object in C:\webroot\wamp\www\index.php on line 12

<?php
$config['db'] = array (
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'pdologin'
);
$db = new PDO("mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
$config['db']['username'], $config['db']['password']);
$query = $db->query("SELECT * 'firstname' FROM 'login'");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['firstname'], '<br>';
}
?>
When I run the code I get error "Fatal error: Call to a member function fetch() on a non-object in C:\webroot\wamp\www\index.php on line 12".
Whats making it error? The only thing I can think of is the SQL query.
This SQL query has two syntax errors in it:
$query = $db->query("SELECT * 'firstname' FROM 'login'");
You can't use a string literal as a table in the FROM clause.
Explanation: different types of quotes do different things in SQL.
Single-quotes are always delimiters for string literals or date literals.
In MySQL, back-ticks are delimiters for table identifiers (as well as columns and other metadata objects).
Double-quotes are delimiters for table identifiers in standard SQL, and in MySQL if you set SQL_MODE=ANSI_QUOTES. But by default in MySQL, double-quotes are the same as single-quotes, delimiting strings and dates.
You also had 'firstname' in your query in an invalid place. I can't tell if you meant that to name a column (if so, you were getting the quote type wrong again), or if you meant it to be a column alias (if so, you can't alias *, you can only alias a single specific column).
So your query should look like this:
$query = $db->query("SELECT * FROM `login`");
Another mistake in your script is that you don't verify that $query is an object of type PDOStatement before calling PDOStatement methods on it. PDO::query() will return false if there was an error in the SQL. false is a primitive value, not an object, so it will naturally not have any methods you can call. So you always have to check the return value before doing anything else with it.
For example:
$query = $db->query("SELECT * FROM `login`");
if ($query === false) {
die(print_r($db->errorInfo(), true));
}