Best practice OOP with MVC and PHP functions? - php

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.

Related

graphaware get a returned count() value

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.

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.

Calling PHP functions from within the same file

I have a php file called choose.php where inside i echo some HTML i.e. a select element.
I am using PDO to populate the select element from a mysql database.
the code i have written works perfectly but when i put it into a function and try to call it i get an error telling me that i cannot declare said method again.
the code is thus:
echo '<select>';
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
while ( $row = $res ->fetch() )
{
echo '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
echo '</select>';
in other words the function would look like this:
function getnames()
{
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
while ( $row = $res ->fetch() )
{
echo '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
}
Why cant i call the method inside the echoed select element?
echo '<select>';
getnames();
echo '</select>';
Also how would i accomplish this by placing the method in another php file to keep it tidy?
Why cant i call the method inside the echoed select element?
Because the method body references $conn, which is supposedly a global variable and not in scope inside the method body. You can verify that this is the problem (and "fix" it) with
function getnames()
{
global $conn;
// the rest as before
}
Now, although this will make the problem go away, what you propose here is not a good way to organize things. There are several issues:
getnames uses a global variable ("invisible argument") -- note that you would not have had reason to ask this question if this had been corrected!
The name of the method is misleading -- it doesn't "get" something, it prints HTML.
The method is unusable for anything else other than its specific purpose -- if you wanted to do something else with the names (e.g. print a table) you would have to write another method.
You are interleaving straight HTML output (the <select> tag) with business logic (querying the database). It's better to do all the business logic up front (keep the results you need in variables) and then do the HTML all in one go.
All of the above are serious deficiencies of the chosen approach and none of them would be present in a well built application. I suggest that instead of making the problem go away you would be better served by refactoring the code to address these, and the problem will fix itself on the way.
Code Review would be an excellent place to ask a question along the lines of "I have this code and this recommendation -- how would I implement it properly?" if you need extra help.
You are trying to access $conn variable which is not available in your function scope.
To access $conn variable inside your function use global, like below:
global $conn;
How are you loading the file in which the getnames function is defined? Try using require_once and making sure it's not being included more than once - already defined means it's be defined and the file is being called again, hence trying to define it again
If you're calling that same code multiple times on your page it will get very heavy to load. I would recommend just running it at the top of the page and putting the data to a variable, then echoing that variable at each location that you need it
So your code in the top of your page
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
$outputData = '';
while ( $row = $res ->fetch() ){
$outputData .= '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
Then
echo '<select>'.$outputData.'</select>';

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all

How do i parse the the value from a string in the function call?

i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}

Categories