Passing a db_query as a parameter - php

I am trying to pass a db_query as a parameter in a function, but I am not getting what I want.
For example
function some_function(){
$query = "SELECT text FROM my_table";
$result = db_query( $query );
$text = other_function( $result );
echo $text;
}
function other_function( &$result ){
$array = db_fetch_array( $result );
return $array['text'];
}
I have verified that the query works and that this works if I don't run it through another function. Any ideas of what I am doing wrong? Any ideas of a better way to do this? I would still like to be able to use a separate function to fetch the arrays from my db_query if possible.

remove the &. It seems unnecessary here. Also, I would use objects for this sort of job, this way you can simply use $this->result or its similarities.

Related

What kind of object can I send to this view in order to get this PHP code to work?

I am terrible at PHP and I need to retrieve data from a database and give it to an index.php view. The view is pre-made and has this code:
//This is simplified - it has error handling that is not shown
$results = getAll($tableName);
//This is the line where it is failing
//Undefined Offset
$columns = empty($results) ? array() : array_keys($results[0]);
$idColumn = $columns[0];
There is all the rest of it but I just need to know what on earth it is that this bit of code is expecting. I have not even got the first clue what is supposed to be sent to this thing. I just need to get it to work.
This is what I have tried so far:
function getAll($tablename)
{
$mysqlConnection = getDbConnection();//Just the normal PDO db connection
$sql = "SELECT * FROM ".$tablename;
$sth = $mysqlConnection->prepare($sql);
$sth->execute();
$resultSet = $sth->fetch(PDO::FETCH_ASSOC);
return $resultSet;
}
I have tried various different PDO::FETCH_... types but nothing is working. There is no information about what it is that I am supposed to send that part of the view.
If you want all the rows from fetch(), you will need to loop through the result set because it will return a single row. In the loop you can place them in an array.
You can use fetchAll() instead. It will return all the results as an array.

PHP Function is only called once in for loop

I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).
I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.
However, the loops only runs once! If I substitute $id with any number it works fine, but only once.
This is a simplified version of my code:
for ($i=0; $i<9; $i++) {
$id = $rows[$i][1];
$values = getDetails($id); // This function (from another file) returns an array
$title = $values["Title"];
$year = $values["Year"];
$query= " INSERT INTO database
VALUES ('','$title','$year')";
$result = $mysqli->query($query);
}
* EDIT This is part of the getDetails function:
function getDetails($id) {
$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);
... // This might look weird and is definatly not perfect, but it works :)
$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}
* EDIT
WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.
I think your $query is wrong.
Change this:
$query= " INSERT INTO database
VALUES ('','$title','$year')";
To something like this:
$query= " INSERT INTO database (field1,field2,field3)
VALUES ('','$title','$year')";
Is your ID field autoincrementing? If so you do not need the "field1" entry at all.
Happy Coding!
I had this problem also.
I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.
SOLUTION: Remove the location redirects and the exit(); from the function.
Hope this helps someone else.

Joomla multiple functions in single model/view

I'm trying to create a drop down list that populates a <select> with options pulled from a DISTINCT argument. Code looks like this:
function cityData() {
$db =& JFactory::getDBO();
$query = "SELECT DISTINCT MSTCITY FROM " . $db->nameQuote('#__mls') . " ORDER BY MSTCITY;";
$db->setQuery($query);
$tbl = $db->loadObjectList();
echo $tbl;
}
Now, I have two views: one is RAW for an AJAX call and the other is the default view. I figured the simplest way would be to just use the default view and do it in PHP, since the default view wasn't really being used for much anyway. So I added a function:
function dropList($tpl = null){
$model = &$this->getModel();
$array = $model->cityData();
$this->assignRef('array', $array );
parent::display($tpl);
}
And then a call in the page
<?php
$thing = $this->array;
echo $thing;
?>
Nothing is being displayed for the echo $thing;. In the past, when I used PHP to build content instead of AJAX, this worked fine. I don't know if it's using loadObjectList() that's not giving me anything or what. I know the mySQL query works, as it's be tested in the cmd and I get the result I expect.
In order to debug and see the array values you need to use print_r.
In your case edit the default.php file to
<?php
$thing = $this->array;
print_r($thing);
?>
You can also use var_dump

Writing SQL Queries in Codeigniter 2.0

I have the following function that does not work and I'm having the hardest time trying to figure it out. I'm 12 and just learning, so forgive me:
function get_answer() {
$answer = $this->db->query("SELECT COUNT(questions) FROM possible_quest WHERE questions='something'");
return $answer;
}
When I run the following SQL query in phpmyadmin, it returns the expected result
SELECT COUNT(questions) FROM possible_quest WHERE questions='something'
How do I get this working in CodeIgniter using my function above?
The PHP error I get is
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Could be:
function get_answer()
{
$query = $this->db->query("SELECT COUNT(questions) AS count FROM possible_quest WHERE questions='something'");
$count = $query->row(); // returns an object of the first row
return $count->count;
// OR
$count = $query->row_array(); // returns an asociative array of the result
return $count['count'];
}
Another thing: if you want to pass 'something' as a variable, you can use parametrized query, like
$sql = "SELECT COUNT(questions) AS count FROM possible_quest WHERE questions = ?";
$query = $this->db->query($sql, array($something));
which has the benefit of escaping automatically your variable, so you don't worry about sql injections.
You need to setup to the count.
Heres what you need to do is
$answer = $this->db->query("SELECT COUNT(questions) as count FROM possible_quest WHERE questions='something'")->first_row()->count;
//$answer is now setup to be count
One line. Thats the beauty of CI
You're getting that error because
return $answer;
should be
return $answer->result();
The error you are getting is related to the fact that $this->db->query returns a result object, so you cannot use $answer directly as a string.
I suggest that you use print_r($answer) to see what could be going wrong with your conversion of objects to strings, if you have such a function in your model.
CodeIgniter has functions for building queries and returning the count:
function get_answer() {
$this->db->from("possible_quest");
$this->db->where("questions", "something");
return $this->db->count_all_results();
}
NOTE: The name of the function 'get_answer' doesn't match what you're actually doing. It looks like you're getting a count of questions, not an answer, so you should name it to something that makes more sense, like 'get_question_count'.
I recommend you to use an Active Record with method chaining when possible:
public function getAnswer() {
return
$this->db->
select('id')->
where('questions', 'something')->
get('possible_quest')->row()->count
;
}
or
public function getAnswer() {
return
$this->db->
select('id')->
from('possible_quest')->
where('questions', 'something')->
get()->row()->count
;
}
It's secure, easy to use, easy to understand and read. Don't listen to people saying that a single-line code is something good because a good code should be readable.

Get the full result

Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all

Categories