How to get fields from db in codeigniter - mysql

I am using mysqli_num_fields() but facing error
I also used mysql_num_fields but again faced error.
$this->db->select('*');
$this->db->from('quizmarks');
$query = $this->db->get();
$data= $query->result();
echo mysqli_num_fields($data);
exit();
Here is the error
A PHP Error was encountered
Severity: Warning
Message: mysqli_num_fields() expects parameter 1 to be mysqli_result, array given

$query = $this->db->get('quizmarks');
return $query->num_fields();
More optimal solution
Use directly get method becoz you need all fields of that table

Related

Getting data from related table in Codeigniter -- translating MySQL query into CI MVC

I have worked with examples from a few different StackOverflow posts to get data from related tables in CI, but haven't been successful in connecting my tables in the "where" part, and I'd like to understand how to translate that from a MySQL query to the CI MVC.
This is the MySQL query that works to get the dctag fields from the dctags table where the dctag_id in the articles table matches:
$dctagger = $article['dctag_id'];
$query = "SELECT `dctitle`, `dctag_id` FROM dctags WHERE dctag_id = '$dctagger'";
$query_run = mysql_query($query);
This is the code for the Model, Controller, and View files:
Model -
public function get_article_dctag() {
$this->db->select('*')
->from('dctags')
->where('dctag_id', $this->$data['dctag_id']);
$query = $this->db->get();
return $query->result_array(); }
Controller -
public function article($slug) {
$data['article'] = $this->article_model->get_article($slug);
$data['dctag'] = $this->article_model->get_article_dctag();
$this->load->view('templates/header-article', $data);
$this->load->view('article', $data);
$this->load->view('templates/footer-home'); }
View -
<?php foreach ($dctag as $dctag_item): ?>
<title><?php $dctag_item['dctitle']; ?></title>
<?php endforeach; ?>
Error -
"A PHP Error was encountered... Severity: Notice... Message: Undefined variable: data...Filename: models/article_model.php" (see Model code above)
The problem is the variable $this->... and I don't know what that needs to be. Thanks for explanations/clarification -- in advance!
If your dctag_id is in $data['article'] then use following code
On Controller
public function article($slug)
{
$data['article'] = $this->article_model->get_article($slug);
$data['dctag'] = $this->article_model->get_article_dctag($data['article']['dctag_id']);
$this->load->view('templates/header-article', $data);
$this->load->view('article', $data);
$this->load->view('templates/footer-home');
}
On your Model
public function get_article_dctag($id)
{
$this->db->select('*')
->from('dctags')
->where('dctag_id', $id);
$query = $this->db->get();
return $query->result_array();
}
In the controller you should pass the variable on the get_article_dctag($var)
This will be the reference on your model get_article_dctag() and this should have a parameter of what you are searching for. In your structure it seems that Model cant locate your $data['dctag_id'] in your function
In the controller
$dctag_id = 2
$this->article_model->get_article_dctag($dctag_id);
In your model
function get_article_dctag($dctag_id){
$this->db->where('dctag_id',$dctag_id);}
Hopes it will help you a lot

can i use where and order by in mysql together?

Can i use where and order by in mysql together like this
$results=mysql_query("SELECT `status_content`
FROM `status`
WHERE `user_id`=".$_SESSION['user_id']."
ORDER BY `status_time` DESC" );
her is my code, but it is giving me error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\lr\profile.php on line 65
<?php
$results=mysql_query("SELECT status_content FROM status
WHERE user_id=".$_SESSION['user_id']."
ORDER BY status_time DESC" );
while($row=mysql_fetch_array($results)) {
echo $row['status_content'];
}
?>
yes, this is valid as google will tell you http://dev.mysql.com/doc/refman/5.0/en/select.html
For your actual error, from the php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
// do something
}
Also: you should not use the mysql_* functions anymmore since they are deprecated and unsafe.
Use mysqli_* or PDO instead.

Fatal error: Call to undefined method CI_DB_mysql_result::last_query()

`$query = $this->db->from('user_notifications');
$query = $query->select('user_notifications.*,users.Firstname as name');
$query = $query->order_by('user_notifications.date_added','desc');
$query = $query->get();
echo $query->last_query();
return $query->result_array();`
error = Fatal error: Call to undefined method CI_DB_mysql_result::last_query() in
Thank you in advance
the syntax will be
echo $this->db->last_query();
see the link http://www.codeigniter.com/userguide2/database/helpers.html
I guess you are using codeigniter & Active Record you can echo the last query by calling
$this->db->last_query();
And is there a reason to assign the outcome of each line to $query ? See below how you can use Active record , Also you query will through the error because you have select users.Firstname in select() but in your from('user_notifications') you haven't mentioned the users table also if there is relation between them do a proper join by seeing usage of Active record
// function start
$this->db->select('user_notifications.*,users.Firstname as name');
$this->db->from('user_notifications,users');
$this->db->order_by('user_notifications.date_added','desc');
$query = $this->db->get();
echo $this->db->last_query();
return $query->result_array();
// function end
Active Record

PDO returning MySQL error with bindParam

Hey Guys I'm running this little function here
function getBeaches() {
$request=Slim::getInstance()->request();
$args=filter_var_array(func_get_args(),FILTER_SANITIZE_STRING);
$sql="SELECT * FROM beaches WHERE state=:state AND city=:city";
// var_export($args); die();
// array ( 0 => 'wa', 1 => 'seattle', )
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue('state', $args[0], PDO::PARAM_STR); //should bind wa
$stmt->bindValue('city', $args[1], PDO::PARAM_STR); //should bind seattle
$stmt->execute();
$stmt = $db->query($sql);
$beaches = $stmt->fetchObject();
$db = null;
echo '{"map": ' . stripslashes(json_encode($beaches)) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
/* {"error":{"text":SQLSTATE[42000]: Syntax error or access violation:
* 1064 You have an error in your SQL syntax; check the manual that
* corresponds to your MySQL server version for the right syntax to use
* near ':state AND city=:city' at line 1}}
*/
}
And am getting the error I commented at the bottom, trying to run this like so
mysql$ SELECT * FROM beaches WHERE state='wa' AND city='seattle';
May be this rings some bells?
You need the semicolons before your param names: (Not 100% true, see edit)
$stmt->bindValue(':state', $args[0], PDO::PARAM_STR); //should bind wa
$stmt->bindValue(':city', $args[1], PDO::PARAM_STR); //should bind seattle
From the PHP docs on PDOStatement::bindValue():
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
EDIT
As #jeroen has pointed out the problem (the same one in your pastebin) that you overwrite the $stmt variable before you get the data from it. In you code the problem is around the 17th line:
$stmt->execute(); // $stmt now has query results (from the query with parameters bounded)
$stmt = $db->query($sql); // You redo the query. Now $stmt has no query results and no parameters are bound
$beaches = $stmt->fetchObject(); // Statement assumes you want to execute query and does so but not parameters are bound
You can remedy this by changing the above lines to:
$stmt->execute();
$beaches = $stmt->fetchObject();
Not sure if it helps, but I always used bindParam over bindValue. If you chose to do so, modify your binders as such:
$stmt->bindParam(':state', $args[0], PDO::PARAM_STR);
$stmt->bindParam(':city', $args[1], PDO::PARAM_STR);
Other than that, everything you're doing looks fine to me.

mysql_query returning boolean or string?

For some reason when I run a $result=mysql_query(...) that should return an array to be parsed with mysql_fetch_array, I keep getting an error that the value returned for $result is either a string or boolean, which mysql_fetch_array() can't work with. I've been running the same query on my server for years and for some reason it stopped working recently.
here's the sample code:
$result=mysql_query("SELECT * FROM `patient_list`");
while ($row=mysql_fetch_array($result)) {
...
}
I recently upgraded to the newest version of wamp. might that have anything to do with it? Any thoughts?
This error means taht result of mysql_query is not valid.Please place
echo mysql_error();
after you call mysql_query
Your problem could be access / database doesn't exist / anything
Always check the query runs correctly execute your query like this :
$result = mysql_query(<query>);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// process the result here
Documentation for mysql_query
Try this:
$result = mysql_query("SELECT * FROM `patient_list`") or die( mysql_error() );