So I have been working around with neo4j and php-client graph aware, until now i have make it work kind of ok. Until now that i try to run a query returning a count() and can't find how to catch the information, the query that i run is the next function:
function net_in_common($user, $other){
global $client;
$searchquery = "MATCH (a:user)-[r:IN_NET]->(b:user)<-[s:IN_NET]-(c:user) WHERE a.username = '" . $user . "' AND c.username = '" . $other . "' return count(DISTINCT b) as incommon";
$result = $client->run($searchquery);
return $result;
}
but when i try to echo it by
$common = net_in_common($user1, $user2);
echo $common->value('incommon');
i get absolute and completely nothing, it even dispatch an error that break the php code but i can't find the mistake itself.
it's a different way of fetching the value of a count() or something that i should do different??
The $result variable in your function returns you a Result object which itself contains a collection of ResultRecord objects (all is explained in the README of the client https://github.com/graphaware/neo4j-php-client#working-with-result-sets).
So, for reading the incommon value you would have to do :
$common = net_in_common($user1, $user2);
echo $common->firstRecord()->get('incommon');
Also, using php functions like this doesn't really reflect how we use php in (almost) 2017, maybe you can share a complete example of your project so we can investigate what's wrong, normally calling the value on a Result object should trigger an exception.
Related
New to OOP so I am trying to figure out best practice. This code is based off an existing script I am adding to.
Most of the threads with this question tell the poster to code as so:
function ($arg1, $arg2){
//some code
}
and call:
function($a1, $a2);
I have an OOP-based function (that works) but it doesn't quite look right and when I try to call it as the suggested method, I get:
Array to string conversion .... on line .. Array
Here's my (working) function that gathers the output:
public function getMail($type, $id = 0) {
$query = $this->db->query("SELECT * FROM km_mail WHERE id = '" . (int)$id . "' AND `type` = '" . $this->db->escape($type) . "'");
foreach ($query->rows as $result) {
$mail_data[$result['title']] = $result['value'];
}
return $mail_data;
}
This is the working (but ugly) part - this returns the database column requested (but looks wrong?):
$this->model_setting_mail->getMail('order')['update_link'];
When I try to request the column like so, the array to string conversion error occurs:
$this->model_setting_mail->getMail('order','update_link');
In my example, order = $type, update_link = $result['value'] and $id = 0 is default, unless an $id is passed.
The first example you show is a shorthand way of selecting an array element from value returned by a function.
$this->model_setting_mail->getMail('order')['update_link'];
Is the same as:
$result = $this->model_setting_mail->getMail('order');
print $result['update_link'];
Second example is passing two values to a function.
They are completely different.
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
return $SelectRowByIncrementQuery;
return $SelectedRow; //HERE is the error <-------------------------------
return $result;
}
$row = $SelectedRow;
echo $row;
if ($row['Id'] === max(mysqli_fetch_assoc($Id))){
$row['Id']=$row['Id'] === min(mysqli_fetch_assoc($Id));#TODO check === operator
}
else if($row['Id']=== min(mysqli_fetch_assoc($Id))){
$row['Id']=max(mysqli_fetch_assoc($Id));#TODO check === operator //This logic is important. DONT use = 1!
Ok, I am trying to write a program for the server end of my website using PHP. Using Netbeans as my IDE of choice I have encountered an error while attempting to write a function which will store a single row in an associative array.
The issue arises when I try to return the variable $SelectedRow. It causes an 'Unreachable Statment' warning. This results in the program falling flat on its face.
I can get this code to work without being contained in a function. However, I don't really feel that that is the way to go about solving my issues while I learn to write programs.
Side Notes:
This is the first question I have posted on SO, so constructive criticism and tips are much appreciated. I am happy to post any specifications that would help an answer or anything else of the sort.
I do not believe this is a so-called 'replica' question because I have failed to find another SO question addressing the same issue in PHP as of yet.
If anybody has any suggestions about my code, in general, I'd be stoked to hear, as I have only just started this whole CS thing.
You can only return one time. Everything after the first return is unreachable.
It's not entirely clear to me what you want to return from that function, but you can only return one value.
The return command cancels the rest of the function, as once you use it, it has served its purpose.
The key to this is to put all of your information in to an array and return it at the end of the function, that way you can access all of the information.
So try changing your code to this:
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
$returnArray = array();
$returnArray["SelectRowByIncrementQuery"] = $SelectRowByIncrementQuery;
$returnArray["SelectedRow"] = $SelectedRow;
$returnArray["result"] = $result;
return $returnArray;
}
And then you can access the information like so:
$selectedArray = SelectRowByIncrementFunc();
$row = $selectedArray["SelectedRow"]
And so forth...
This is the one thing that I am trying absolutely first time. I have made few websites in PHP and MySQL as DB but never used functions to get data from database.
But here is the thing that I am trying all new now as now I want to achieve reusability for a bog project. I wanted to get the order details from DB (i.e. MySQL) through PHP Function. I am bit confused that how to print values returned by a PHP function.
Function wrote by me is as below:
function _orderdetails(){
$sql = "Select * from orders WHERE 1";
$result = DB::instance()->prepare($sql)->execute()->fetchAll();
return $result;
}
Please let me know how i can print these values and value returned by above function is an array.
I tried by calling function directly through print_r(_orderdetails());
Please let me know:
Efficient way of iterating through this function to Print Values.
Is there any other approach that can be better worked upon?
You cannot chain fetchAll() to execute() like this.
Besides, for a query that takes no parameters, there is no point in using execute(). So change your function like this
function _orderdetails(){
$sql = "Select * from orders WHERE 1";
return DB::instance()->query($sql)->fetchAll();
}
and so you'll be able to iterate results the most natural way
foreach (_orderdetails() as $order) {
echo $order['id'] . '<br />';
}
You can also use ->fetch();
Instead of ->fetchAll();
There some other functions that also work as a worker to iterate through the next row in the table.
You can check PDO for more functions at:
http://php.net/manual/en/book.pdo.php
In your PHP code that will call this function use the following
print_r(_orderdetails());
//to get all the result set... I mean all the values coming from this function.
You can also use the function and use -> after the function call, then put the variable name as follows:
To iterate through the values of this function:
$value_arr = _orderdetails();
foreach ($valur_arr as $value) {
echo $value . '<br />';
}
This way you will echo 1 column from the database table you are using.
For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.
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.