laravel simple query builder (join & where case) - sql

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);

Related

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();

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

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');

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));
}

Extbase - get created sql from query

i want to get some database tables from my typo3 extensions.
The Extension is based on extbase.
The query always returns nothing but the data exists
I've tried this:
$query = $this->createQuery();
$query->statement('SELECT * FROM `my_table`
WHERE field = ? ORDER BY date DESC LIMIT 1',
array($condition));
$results = $query->execute();
and this:
$query = $this->createQuery();
$query->matching($query->equals('field', $condition));
$query->setOrderings(array('date' => Tx_Extbase_Persistence_QueryInterface::ORDER_DESCENDING));
$query->setLimit(1);
$results = $query->execute();
both returns null as result.
Is it possible to get the sql that the class creates to look where the bug is?
I've looked in some extbase persistent classes but didn't find a clue
EDIT:
For those who are interested.. i found a "solution".
If you create the query with the statement() method, you can print the query with this function
echo $query->getStatement()->getStatement();
It doesn't replace the placeholder.
But you can get the Variables with this method
var_dump($query->getStatement()->getBoundVariables());
Thats the best Solution that i found, without editing the extbase extenstions
In TYPO3 6.2 you can use Extbase DebuggerUtility to debug the query.
Add this code before $query->execute():
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbQueryParser');
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($queryParser->parseQuery($query));
For TYPO3 8.7+ use this code instead:
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtilityGeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser::class);
$doctrineQueryBuilder = $queryParser->convertQueryToDoctrineQueryBuilder($query);
$doctrineQueryBuilderSQL = $doctrineQueryBuilder->getSQL();
$doctrineQueryBuilderParameters = $doctrineQueryBuilder->getParameters();
Check this snippet, although it's not very comfortable in use it helps a lot:
in general you need this code at the end of the buildQuery(array $sql) method (*) - right before return $statement;
if (in_array("your_table_name", $sql['tables'])) {
var_dump($statement);
print_r($statement);
}
(*) Class file:
TYPO3 ver.: 4.x: typo3/sysext/extbase/Classes/Persistence/Storage/Typo3DbBackend.php
TYPO3 ver.: 6.x: typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php
In 6.2.x ...
You can try within \TYPO3\CMS\Core\Database\DatabaseConnection::exec_SELECTquery method, just add the condition after fetching the $query, like (trim is important!):
public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
$query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
if (trim($from_table) == 'fe_users') {
DebuggerUtility::var_dump($query);
}
// rest of method
An easy way without changing any Typo3 core code and not mentioned in any forum so far is using the php "serialize()" method:
$result = $query->execute();
echo (serialize($result));
In the result object you find the SQL query ("statement;" ...)
Improvement to biesiors answer:
As Extbase replaces some placeholders after calling buildQuery(), you might prefer to place the debug output into getObjectDataByQuery(), just after $this->replacePlaceholders($sql, $parameters, $tableName);
if (strpos($sql, "your_table_name.")) {
debug($sql, 'my debug output');
};
Also, better use debug() instead of var_dump().
[File: typo3\sysext\extbase\Classes\Persistence\Generic\Storage\Typo3DbBackend.php. Line 339 in version 6.1]:
$query = $this->createQuery();
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$getHotelInfo = 'SELECT * FROM `my_table` WHERE field = ? ORDER BY date DESC LIMIT 1';
return $query->statement($getHotelInfo)->execute();
For executing query you have to write 'setReturnQueryResult' on your repository
I just extended the above snippet, with a $_GET condition.
for debugging, just append "?dbg_table=tx_some_of_my_tables" to your address, and you're ready to go ;-)
if (in_array($_GET['dbg_table'], $sql['tables'])) {
echo('<div style="background: #ebebeb; border: 1px solid #999; margin-bottom: 20px; padding: 10px;"><pre style="white-space: normal">'.$statement.'</pre></div>');
}
A cleaner way to debug your statements when using TYPO3 6.1 is to use the query parser of Typo3DbBackend.
$parser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbBackend');
$params = array();
$queryParts = $parser->parseQuery($query, $params);
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('query', 'my_extension', 1, array('query' => $queryParts, 'params' => $params));
The parser returns an array containing the different parts of the generated SQL statement.
With TYPO3 6.2 the parseQuery method was moved to Typo3DbQueryParser and lost its second parameter.
i suggest set this in typo3conf/LocalConfiguration.php file under 'SYS' array
'SYS' => array(
......
'displayErrors' => 1,
'sqlDebug' => 1
.......
)
and then write wrong field name in query intentionally and then execute code.
this will show last query execute with error.

sql update codeigniter

I am using codeIgniter..
I want to update a table column is_close when id=$ticket_id of my table= tbl_tickets.
I am doing this :-
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
and I have also done this :-
$sql = "UPDATE tbl_tickets SET is_close={1} WHERE id='$title_id'";
$this->db->query($sql);
both are not working,i.e., my table is not updating the value to 1 and also no error is being shown in the broswer. :(
Edited: Included my model part :
function setClosePost($title_id){
$sql = "UPDATE tbl_tickets SET is_close=0 WHERE id='$title_id'";
$this->db->query($sql);
// $data=array(
// 'is_close'=>1
// );
// $this->db->where('id',$title_id);
// $this->db->update('tbl_tickets',$data);
}
My controller :-
function closePost(){
$this->load->model('helpdesk_model');
$this->helpdesk_model->setClosePost($this->input->post('title_id'));
}
first of all use a get method to check if ticket_id is exist or not.
another thing is always use return in your functions in models so you can check them by if(function_name){...}else{...}
then if your get method returned data correctly try
Model Method
public function set_closed($ticket_id){
$this->db->set(array(
'is_close'=>1
)); // pass fields in array
$this->db->where('id',$ticket_id);
$this->db->update('tbl_tickets'); // table name
return true;
}
then check that in your controller
if($this->Ticket_model->set_closed($ticket_id) == true){
echo 'ticket set to closed correctly';
}else{
echo 'there is some error on updating database'.$this->db->error(); // to checkout db error .
}
First, check $title_id before passing:
var_dump($title_id);
Then, try do "select a row with this id" before updating and after.
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
Then, give your table structure.
Just try like this
$sql = "UPDATE tbl_tickets SET is_close='1' WHERE id=".$title_id;
$this->db->query($sql);
just try like this
**function edit($close,$id) {
$sql = "UPDATE tbl_tickets SET is_close= ? WHERE id = ? ";
$this->db->query($sql, array($close,$id));
}**
To handle this type of errors, i mean if reflection is not happen in database, then use below steps to resolve this type of error.
1) use $this->db->last_query() function to print query, using this we can make sure our variable have correct value (should not null or undefined), using that we can make sure also SQL query is valid or not.
2) If SQL query is valid then open phpmyadmin & fire same query into phpmyadmin, it will return error if query columns or table names are invalid.
Use this way, its best way to cross check our SQL queries issues.
I hope it will work.
Thanks
You are trying to update integer(INT) type value, just cross check with your column datatype if that is varchar then you have to put value in a single or double quote.
Like this
$data=array('is_close'=> '1');