I've created a web app using code igniter 3 to get data from 3 tables and display them in the view (quiz_table,question_table and answers_table).
Below is the model code,
function getSingleQuizQuestionDataFromDB($quizId)
{ //insert query
try {
$this->db->select('quiz_table.quizName');
$this->db->select('quiz_table.creatorName');
$this->db->select('quiz_table.rating');
$this->db->select('question_table.questionId');
$this->db->select('question_table.questionTitle');
$this->db->select('question_table.correctAnswer');
$this->db->select('answer_table.answer');
$this->db->from('quiz_table');
$this->db->where('quiz_table.quizId',$quizId);
$this->db->join('question_table','question_table.quizId = quiz_table.quizId','INNER');
$this->db->join('answer_table','answer_table.questionId= question_table.questionId','INNER');
$this->db->from('quiz_table');
$this->db->group_by(['quiz_table.quizId', 'question_table.questionId']);
$result = $this->db->get();
$singleQuizQuestionData= $result->result_array();
return $singleQuizQuestionData;
} catch (Exception $e) {
// log_message('error: ',$e->getMessage());
return;
}
}
When I try to load the result I get the below error
Please help!
Using multiple from() clauses are not allowed in Codeigniter. Removing the second from() will fix the issue
$this->db->from('quiz_table'); <---- here
$this->db->where('quiz_table.quizId',$quizId);
$this->db->join('question_table','question_table.quizId = quiz_table.quizId','INNER');
$this->db->join('answer_table','answer_table.questionId= question_table.questionId','INNER');
$this->db->from('quiz_table'); <---- here
$this->db->group_by(['quiz_table.quizId', 'question_table.questionId']);
Related
I've created a web app using code igniter 3 to get data from 3 tables and display them in the view (quiz_table,question_table and answers_table).
Below is the code in my controller,
public function loadSingleQuizData_get()
{
$quizId = $this->uri->segment(3);
$this->load->model('QuizModel');
$singleQuizQuestionData = $this->QuizModel->getSingleQuizQuestionDataFromDB($quizId);
$data = array('singleQuizQuestionData' => $singleQuizQuestionData);
print json_encode($data);
}
and below is the code in the model
function getSingleQuizQuestionDataFromDB($quizId)
{ //insert query
try {
$this->db->select('quiz_table.quizName');
$this->db->select('quiz_table.creatorName');
$this->db->select('quiz_table.rating');
$this->db->select('question_table.questionId');
$this->db->select('question_table.questionTitle');
$this->db->select('question_table.correctAnswer');
$this->db->select('answer_table.answer');
$this->db->from('quiz_table');
$this->db->where('quiz_table.quizId',$quizId);
$this->db->join('question_table','question_table.quizId = quiz_table.quizId','INNER');
$this->db->join('answer_table','answer_table.questionId= question_table.questionId','INNER');
$this->db->from('quiz_table');
$this->db->groupBy(['quiz_table.quizId', 'question_table.questionId']);
$result = $this->db->get();
$singleQuizQuestionData= $result->result_array();
return $singleQuizQuestionData;
} catch (Exception $e) {
// log_message('error: ',$e->getMessage());
return;
}
}
When I try to load the results in the view I get the below error message
Please help!
https://codeigniter.com/userguide3/database/query_builder.html
The syntax for group by in codeigniter is group_by not groupBy (that would be laravel)
I define a query to delete a table in database. After that i want to show a message that the query was run successfully. How can I check it with an if statement?
$query = DB::table('user_users')->delete();
return view('datenbank');
When you use delete with the query builder it will return the number of affected rows.
Your if statement would just need to look something like:
$query = DB::table('user_users')->delete();
if ($query) {
//query successful
}
If you want to be more explicit you could do if ($query > 0) {}
If anything goes wrong with the query (an error) it will throw an Exception which will mean that no rows have been affected.
Personally, I think the best solution is to use an if statement like this.
your code
$query = DB::table('user_users')->delete();
return view('datenbank');
Soluction
$query = DB::table('user_users')->delete();
// check data deleted or not
if ($query > 0) {
return response()->json('202 Accepted', 202);
} else {
return response()->json('404 Not Found', 404);
}
If the query did not execute successfully, Laravel would normally throw an error. But if you want to be really sure, you could query the table right after truncating it to make sure there is no data left.
DB::table('user_users')->delete();
// Test if no records are left in the table
$success = DB::table('user_users')->count() === 0;
return view('datenbank', compact('success'));
I will recommend to use try catch because laravel query throw exception when some error occur...
$queryStatus;
try {
DB::table('user_')->where('column',$something)->delete();
$queryStatus = "Successful";
} catch(Exception $e) {
$queryStatus = "Not success";
}
return view('datenbank')->with('message', $queryStatus);
you can do try catch with DB Transaction
try {
DB::beginTransaction();
// your code
DB::commit();
}catch (Exception $e) {
DB::rollback();
// other actions
}
I'm trying to cover all my bases in the event my MYSQL database returns any errors (no rows, no connection, no table, etc...) when I'm making a query using CodeIgniter 3.
I have a helper function that returns the latitude and longitude based on a zip code provided. It will always only return a single row (granted the record exits). Here's my helper function as of now:
if (!function_exists('get_coordinates_from_zipcode')) {
//gets latitude and longitude coordinates from supplied zipcode. Returns array
function get_coordinates_from_zipcode($zipcode) {
$ci =& get_instance();
$ci->load->database();
$query = $ci->db->get_where('Geo', array('zip =' => $zipcode))->row_array();
if (!$query) {
return FALSE;
} else {
return $query;
}
}
//* Fields returned from geolocation database *//
/* -zip
-lat
-lng
// Returns false on error or no records
*/
}
And here is my View I'm using (passing $data['array'] array to it from my Controller):
<?php if ($array == FALSE || !$array) : ?>
<?php echo "No data returned"; ?>
<?php else : ?>
<?php echo $array['zip'] . ' is located at ' . $array['lat'] . ' and ' . $array['lng']; ?>
<?php endif; ?>
This works well if there are no rows, but I want to handle any other issues, such as more than one row (highly unlikely to happen), or if there's a problem connecting to the database or table.
I've tried this in my Helper
if ($ci->db->error()) {
return $ci->db->error(); //
} else {
return $query;
}
When I do this, and purposely use an invalid zip code to pass the error to the view, $ci->db->error() always returns array(2) { ["code"]=> int(0) ["message"]=> string(0) "" } and is empty. And of course I get errors that Undefined index: lat and Undefined index: lng
Should I be passing the $ci-db->error() array to the view and acting on it there?
I just want to make sure all my bases are covered. In my mind I should be handling errors in the Helper function but the error() always seems to be empty even when there's an error (such as no rows, or no db connectivity, or no table by that name.
I feel like
if (!$query) {
return FALSE;
} else {
return $query;
}
inside my helper function won't cover all problems I could potentially have connecting to the database.
Why don't you just do the following:
if (!function_exists('get_coordinates_from_zipcode')) {
//gets latitude and longitude coordinates from supplied zipcode. Returns array
function get_coordinates_from_zipcode($zipcode) {
$ci =& get_instance();
$ci->load->database();
if ($ci->db->conn_id === false) {
return false; // connection couldn't be established
}
$query = $ci->db->get_where('Geo', array('zip =' => $zipcode));
if ($query && $query->num_rows() == 1) {
return $query->row_array();
}
return false;
}
//* Fields returned from geolocation database *//
/* -zip
-lat
-lng
// Returns false on error or no records
*/
}
This way:
You test that query didn't return a FALSE result
You test that you are only getting 1 row
You make sure you have established a connection to the db (seems a bit overkill)
Please note: you should always check the value of num_rows() before attempting to access the result array/object. If there are no rows, then you will get undefined indexes when attempting to access the array.
i don't understand the purpose of your helper here - If you dont use a model and if you bypass the controller here why do you even use Codeigniter at first ?
Now your question
if its possible i would create a model where you handle all the errors and try to throw them via Exceptions
a possible approach
Model
class Geo_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_coordinates_from_zipcode($zipcode = false)
{
if (!$zipcode) throw new InvalidArgumentException('Zipcode should be set');
$query = $this->db
->select('*')
->from('Geo')
->where('zip', $zipcode)
->get();
$arrError = $this->db->error();
if (isset($arrError['message']) && !empty($arrError['message'])) throw new RuntimeException($arrError['message']);
if ($query->num_rows() != 1) throw new RuntimeException('Query - Number of rows should be 1');
return $query->row_array();
}
}
controller
class Geo extends CI_Controller
{
public function coordinatesfromzipcode($zipcode)
{
$this->load->model('Geo_model');
try
{
$row = $this->Geo_model->get_coordinates_from_zipcode($zipcode);
//load your coordinates view
}
catch (Excepetion $e)
{
//load an error view or something like that...
echo $e->getMessage();
}
}
}
I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
$like = Like::firstOrNew(array('property_id' => $id));
$user = Auth::id();
try{
$liked = Like::get_like_user($id);
}catch(Exception $ex){
$liked = null;
}
if($liked){
$liked->total_likes -= 1;
$liked->status = false;
$liked->save();
}else{
$like->user_id = $user;
$like->total_likes += 1;
$like->status = true;
$like->save();
}
return Redirect::to('/detalle/propiedad/' . $id);
}
// Model
public static function get_like_user($id)
{
return static::with('property', 'user')->where('property_id', $id)
->where('user_id', Auth::id())->first();
}
// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController#storeLike'));
#Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){
Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();
I have a function in my class which is not completed. I'm searching a way to do it all night long. Well I want to fetch all the result of a SELECT request to MYSQL using PDO in a OOP class/function.
Here my function
function select($query)
{
try
{
$sql = $this->connect->query($query);
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
return ????
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
I know that I can do it with a while loop, I tested a few options but most of the time I only got 1 result. Anyone a point for me, where I could start my search for a solution to this issue?
It's pretty easy, actually. You use PDO::FETCH_CLASS and specify which class you want to instantiate for each row.
Here is an example that fetches all available rows as an array of objects of class YourClassName.
function select($query) {
try {
$sql = $this->connect->query($query);
return $sql->fetchAll(PDO::FETCH_CLASS, YourClassName);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
Only use $sql->fetch(PDO::FETCH_ASSOC) within the while loop, not before, as you have it.
So, like:
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// something
}