I'm trying to show the name of table in my database. I write this code :
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList = $data[0];
}
return $tableList;
}
It give to me only the last table ?
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$tables = queryAll($db,$query);
print_r($tables);
Each time you are looping through the results, your are overwriting the variable tableList. Instead, you need to append to an array of results.
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
$tableList = array();
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
array_push($tableList, $data[0]);
}
return $tableList;
}
try this
`
function affiche_liste()
{$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList[] = $data[0];
}
return $tableList;
}
`
i hope it'll work...
here your array is overwitting every time...that's the reason you were getting the last table name....so you need to append to the existing array...
Related
I have two list-filtering inputs, if used individually they work perfectly but when used together it returns an empty object.
the filters contain one simple search Input field, and one select.
they trigger an API call to the server which when used both looks like this
http://127.0.0.1:8000/api/user?&search=jom&type=admin
the method which this call trigger looks like this
public function index(Request $request) {
$search = $request->input('search');
$type = $request->input('type');
$user = User::select('*');
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
...
the method checkSearch looks like this
private function checkSearch(&$query, $search) {
if (!isset($query)) {
return $query;
}
if (!is_null($search)) {
$searchTerms = $this->stringToArray($search, ' ');
$query = $query->where(function ($query) use ($searchTerms) {
for ($i = 0, $max = count($searchTerms); $i < $max; $i++) {
$term = str_replace('_', '\_', mb_strtolower('%' . $searchTerms[$i] . '%'));
$query->whereRaw("(Lower(name) LIKE ?)", [$term, $term])
->orWhereRaw("(Lower(bio) LIKE ?)", [$term, $term]);
}
});
}
}
and the filterUserType like this
private function filterUserType(&$query, $type) {
if (!isset($query)) { return $query; }
if (!is_null($type)) {
$query = $query->where( 'type', $type);
}
}
I've tried to check the where on the filterUserType method, to orWhere but this just returns values of both not combined.
I triggered a break on the raw query and it appeared like this
select * from `users` where ((Lower(name) LIKE %jom%) or (Lower(bio) LIKE %jom%)) and `type` = %jom%)
When I switched the methods I got the right results.
Switching from
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
to
$this->filterUserType($user, $type); // filter user type
$this->checkSearch($user, $search); // check for search
Still don't know why but it worked
I'm trying to make a module for Drupal 7.x. At a certain point I want to use a sql query (JOIN). When I try the query in MYSQL it works. But when I want to try it in Drupal, the array is empty.
So I guess there is a difference between the sql query and the drupal query (mayby the implemantion is different).
SQL Query
SELECT * FROM friends
INNER JOIN users
ON friends.uid=users.uid
Drupal implementation
function project_myfriends(){
// Use database API to retrieve tasks
$query = db_select('friends', 'f');
$query->join('users', 'u', 'f.uid = u.uid'); // JOIN
$query->fields('u', array('name'))
->execute();
return $query;
}
/**
* Implements hook_block_view().
*/
function project_block_view($delta = ''){
switch ($delta) {
case 'project':
$block['subject'] = t('My Friends');
// Use our custom function to retrieve data
$result = project_myfriends();
$items = array();
var_dump($result);
foreach($result as $friend){
$items[] = array(
'data' => $friend->name,
);
}
// No tasks
if (empty($items)) {
$block['content'] = t('No friends.');
}
else {
// Pass data trough theme function
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
return $block;
}
Thx in advance
You forgot to fetch your result query:
$result = project_myfriends()->execute()->fetchAll();
var_dump($result);
I would like to set an array in an where clause.
function rapport_detail_opbrengsten($idKlant){
$this->db->from('Project');
$this->db->join('Opbrengsten', 'Opbrengsten.idProject = Project.idProject');
if ($idKlant > 0){
$this->db->where('idKlant', $idKlant);}
$query = $this->db->get();
$project = array();
foreach($query->result() as $row){
$project[] = $row->idProject;
}
return implode("`,`", $project);
$this->db->select('idProject, SUM(Prijs) as total');
$this->db->from('Opbrengsten');
$this->db->where_in('idProject', $project);
$this->db->group_by('idProject');
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
}
The return gives the following: string(66) "7,14,14,81,81,81,14,9,15,11,12,6,6,6,`6"
But somehow this doesnt work in the where_in or the where clause.
you are miss using backticks there you need quotes.Change your where_in() to
$this->db->where_in("idProject",$project);
/* $project should be an array containing list of ids not a string */
According to Active Record in where_in() you can pass array of values in second argument
Or just use where()
$this->db->where("idProject IN('".join("','",$project)."')",FALSE);
When I execute the function below query execute successfully but I get a warning above the result the query:
mysql_num_rows() expects parameter 1 to be resource, boolean
How do I fix this?
public function retrieve()
{
$id=JRequest::getVar('id');
$db =JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='$id' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$db->setQuery($sql);
$db->query();
$row = $db->getNumRows();
if($row == 1) {
return $db->loadAssocList();
} else {
$db = JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='$id' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";
$db->setQuery($sql);
return $db->loadAssocList();
}
}
Your code has several issues.
Never use unchecked/unvalidated request values, not even in examples!
Use the query builder.
Reduce coupling by a) setting the database in the constructor, which is done already in models, and b) retrieve the id in the controller.
You try to get all fields (*) from multiple tables, which have some column names in common. That will not work.
Have a look at JOINs.
This will work:
public function retrieve($id)
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car', '#__npco_namayeshgah', '#__npco_agahi'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_namayeshgah.id_namayeshgah = #__npco_agahi.id_namayeshgah');
$query->where('#__npco_car.car_id = #__npco_agahi.car_id');
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
if (empty($rows))
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car, #__npco_useragahi, #__npco_user'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_user.id_user = #__npco_useragahi.id_user');
$query->where('#__npco_car.car_id = #__npco_useragahi.car_id');
$db->setQuery($sql);
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
}
return $rows;
}
may be this is your issue..
Change your query as following
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='".$id."' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='".$id."' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";
I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);