Mysqli query returns an emptry string - php

I'm dealing with an issue where the mysqli library in PHP doesn't seem to return a longtext column. I can get the value of the column using both console and PHPMyAdmin but mysqli returns nothing but an empty string.
Here's the function I'm using:
public function greetings_get() {
$output = array();
$greetings_query = "SELECT `engagement_data`.`data`, `engagement_users`.`name` FROM `engagements`, `engagement_data`, `engagement_users` WHERE `engagements`.`promo_slug` = 'stod2.hm2013' and `engagements`.`user_fbid` = `engagement_users`.`fbid` and `engagement_data`.`engagement_id` = `engagements`.`id` ORDER BY RAND() LIMIT 0,5";
$greetings = $this->db_connection->prepare($greetings_query);
$greetings->execute();
$greetings->bind_result($gr_data, $gr_name);
while ($greetings->fetch()) {
$output[] = array('message' => $gr_data, 'name' => $gr_name);
}
return $output;
}
In this case, $gr_data is an empty string, while $gr_name returns a value. –Strange isn't it?
Is there something I'm doing wrong?

According to this answer at php.net, you must use mysqli_stmt::store_result before you bind the result
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
This
$greetings->execute();
$greetings->store_result();
$greetings->bind_result($gr_data, $gr_name);
should fix it.

Related

Issue with returning value in php function

I'm new in programming and especially with php and MySQL. I have to create dynamic web site for homework. My problem is with the function below. I want it to return int value of tag by given tag name (string). But in my case the function returns every time '1'. Can anyone help me to solve this problem, thanks.
public function getTagIdByName(string $tagName) : int
{
$statement = self::$db->prepare("SELECT tags.id FROM tags WHERE tags.name = ? ");
$statement->bind_param("s", $tagName);
$result = $statement->execute();
return $result;
}
The problem is that you're returning the result of execute(), but that function doesn't actually give you your query result. You need to fetch results after making sure the execution was successful.
//don't forget to error-check before using query results
$statement->execute() or die($statement->error);
$result = $statement->get_result(); //retrieve results for processing
if(!$result->num_rows) return null;//if the id was not found in the DB
else return $result->fetch_assoc()['id'];
You can achieve easily with
$data = $result->fetch_assoc();
return $data['id']; // you can change with which you want to return with field name
And whichever you can use your returned values.

PHP mysql result issue

I have this line in my registration page.
if (device_id_exists($_POST['device_id']) == true) {
$errors[] = 'Sorry the Serial Number \'' . htmlentities($_POST['device_id']) . '\' does not exist.';
}
I have this in my function page.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$numbers'");
return (mysql_result($query, 0) == 0) ? true : false;
If I run this query SELECT COUNT(numbers) FROMdevicenumbersWHEREnumbers= '1234567890'
(a valid number) it will return 1 = match found right? If I put a bogus number it returns a '0'.
What is happening is when there is a valid number it still returns the error the number doesn't exist. If I change it to the result to == 1 it will submit any number? Im a newbie to DB calls any help appreciated. I hope I provided enough info.
Looks like you're calling the incorrect variable. Within the device_id_exists() function, you're accepting a variable named $device_id. However when you're performing the query, you're calling what appears to be an undefined variable: $numbers. I suspect $numbers should be renamed to $device_id.
I see your $device_id comes from a form post. I'd HIGHLY recommend you escape the variable, using mysql_real_escape_string() to ensure you are protected against SQL injection. Please note that sanitize() does NOT protect against SQL injection!
On one additional note, I'd recommend utilizng mysql_num_rows() rather than mysql_result() because mysql_result() actually asks the database server to return an actual result when all you really care about is whether the entry exists or not, not it's actual value.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$device_id = mysql_real_escape_string($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$device_id'");
return mysql_num_rows($query) ? True : False;
}
I had a similar problem with mysql result set , It returns nums_rows == 1 even when there are no records (while using max() inside select query - In your case you have used count())... Instead of checking mysqlquery to 0, check it whether the result set empty (That's how i solved my problem).. eg. if(!empty(mysql_result($query))) ? true : false;

How to get a PDO Fetch( ) to return as string

How can I get a PDO to return the data as a string not an array? I am not sure this is possible so if not is there a way to convert the array to a string after it has been processed?
My code which is returning the string is:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
I have tried different fetch types such as FETCH_CLASS FETCH_OBJ
You can do it like this:
echo $stmt->fetchColumn();
Or:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[0];
$result = $statement->fetchColumn();
This work for me, the only thing I noticed here is that fetchColumn() always refer to first column on your table. You need to adjust / re-position the only column needed to the first-column on your table or make an Sql query i.e "SELECT" query to get the only column needed. Thanks

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.

php +codeigniter sql query

I want to do a query in my model from a table known as jurisdictions. Now I want this query to provide a valid MySQL result resource. I.e I want to pass the result to mysql_fetch_array(). If I pass in $query = $this->db->query(). I get an error saying that the passed in argument is invalid. I was wondering how can I convert $query to a MySQL result recource.
Well, if you want to have a MySQL resource, you should be using mysql_query.
Codeigniter already has a method which will give you one row at a time: row_array (actually, it has two, the other is just row, but that returns an object, not an array). If you want to get numeric indexes on the result of result_array, use array_values:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$aso_arr = $result->row_array(); // assoc. array w/o numeric indexes
echo $aso_arr[ 'foo_rules' ];
$num_arr = array_values( $aso_arr );
echo $num_arr[ 0 ];
If you would like the entire result of the selection, then use result and result_array (they have behavior similar to row and row_array, only they return the whole result set in an array)
EDIT
I repeat my first sentence, but you can get the MySQL resource this way:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$resource = $result->result_id;
But, since this is not documented, it should not be considered supported or even expected behavior. Be forewarned.
If I'm understanding you correctly then why not just use the available methods of:
$query->result();
or
$query->result_array();
Choose whichever to suit your needs.

Categories