I am using the slim framework to create an api which contain a route to get all accounts from my database. I try to return the list of accounts in json but it remove the last two characters which makes it an invalid Json because it is expected to end with }]. I do not know why it is doing that and how to solve it.
<?php
header("Content-Type: application/json;charset=utf-8");
class Account {
public function getAll(){
$db_connection = new Connection();
$conn = $db_connection->getConnection();
$result = $conn->query("SELECT * from accounts");
$numrows = $result->rowCount();
if ($numrows > 0) {
$rowset = $result->fetchAll(PDO::FETCH_ASSOC);
}
else {
$message['Error'] = 'No Account found';
$rowset = $message;
}
return $rowset;
}
}
I am calling the getAll method in my route like
$app->get('/Account/GetAll', function($request, $response, $args) use ($app){
$application = new Account();
return $response->withJSON($application->getAll());
});
You have some whitespace outside of PHP tags. The most likely case is that you have a blank line above a <?php. Alternatively, you may have a two blank lines after a ?>.
Related
I'm very new to PHP and Slim Framework which helps creating APIs.
Everything is ok If i query db inside $app->post or get. But I want to separate it to normal function. It will help when I need to use it later in other APIs.
I tried to call this
$app->get('/search/[{phone}]', function($request, $response, $args) use ($app){
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($token)){
return $this->response->withJson("valid");
}
return $this->response->withJson("invalid");
});
My isTokenValid() function
function isTokenValid($token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
But I get 500 Internal Server Error
Type: Error
Message: Call to a member function prepare() on null
File: /Applications/MAMP/htdocs/aigoido/src/functions.php
Line: 25
How to call it outside $app? Thanks.
You want to create a dependency injection container for your database connection and pass that object in as the function parameter rather than app object. This makes the db connection reusable throughout your app.
https://www.slimframework.com/docs/concepts/di.html
Also, you can return $response rather than $this->response.
$c = $app->getContainer();
$c['db'] = function() {
return new DB($host,$user,$pass,$name);
};
$app->post('/search/[{phone}]', function($request, $response, $args) use ($c) {
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($c->db,$token)){
return $response->withJson("valid");
}
return $response->withJson("invalid");
});
function isTokenValid($db, $token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $db->prepare($sql);
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
Pass $app to your function as parameter. The function has it own context so $app is not available without that.
function isTokenValid($token, $app){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
Undefined variable: data in my view
This is a simple display data in the input.
So, why this input isn't display my query result at it?
my view
<input type="text" name="sitename" value="<?php echo $data['sitename']; ?>"><br>
model
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
$num = mysqli_num_rows($sqli);
while ($num > 0)
{
$data = mysqli_fetch_array($sqli);
$num--;
}
return $data;
}
}
Simply because a variable is declared somewhere, doesn't mean it is available everywhere. All variables have scope in which they are accessible. See this: http://php.net/manual/en/language.variables.scope.php for more information on scope.
You need to pass the $data variable into your view. I image you're using some sort of MVC framework since you have a model and a view. If this is the case you can lookup how to pass variables into views in that specific framework. The basic structure of your controller method might look something like this:
//sudo code - not specific to an actual framework
public function controller_method()
{
$data = $model->getData();
$this->template->set('data',$data);
$this->template->load('view');
}
Just search how to do that in your specific framework. Hope that helps!
EDIT
Base on your comment it looks like you're setting data after you load the view. You need to swap the order and call $display = new Display("main"); $data = $display->getData(); before you include'../model/display.php';
If the query returns 0 rows, your while() loop will never execute, so it won't set $data.
Since you're only returning 1 row from the query, you don't need a loop, you can just use an if. Then you can return $data only when it succeeds.
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
if ($data = mysqli_fetch_array($sqli))
{
return $data;
}
else
{
return null;
}
}
}
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.
I have written a php class to use in a small script to just run any query that I like from other scripts. This is NOT going to be used publicly or in production, and I'm aware of the huge security issue this poses!
I have done this as an excercise to see learn about classes etc... I seem to be having problems with one specific line in the code which is causing an error somewhere. I think it might be because I'm trying to return an array, and I think I haven't defined it properly in the class.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
This is the whole code.
<?php
class GetRandomRecord {
//Connection
public $CUDBName;
public $CUHost;
public $CUUser;
public $CUPassword;
public $in_SQL;
public $out_Resource;
public $CULink;
public $message;
public $errors = array(); // is this correct?
public $resultOfQuery = array(); // is this correct?
/****************************************************************/
public function setSQL($value){
$this->in_SQL = $value;
return $this->in_SQL;
}
/****************************************************************/
public function setConnectionString($db,$host,$user,$password){
$this->CUDBName = $db;
$this->CUHost = $host;
$this->CUUser = $user;
$this->CUPassword = $password;
}
/****************************************************************/
public function runSQL() {
$this->CULink = mysqli_connect( $this->CUHost , $this->CUUser , $this->CUPassword , $this->CUDBName);
if (mysqli_connect_errno()) {
$this->message = "Connection failed: ".mysqli_connect_error();
return $this->message;
}
$this->out_Resource = mysqli_query($this->in_SQL , $this->CULink);
if (!$this->out_Resource)
{
$this->errors['sql'] = $this->in_SQL;
$this->errors['eeDBName'] = $this->CUDBName;
$this->errors['eeLink'] = $this->CULink;
$this->errors['status'] = "false"; //There was a problem saving the data;
mysqli_close($this->CULink);
return json_encode($this->errors);
}
else
{
// success
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
mysql_close($this->CULink);
return $this->resultOfQuery;
} // if (!mysql_query( $CUDBName , $sql , $CULink))
}
/****************************************************************/
}//class
$recordGet = new getRandomRecord();
$recordGet->setConnectionString('databasename','localhost','username','password');
// select count from database
$tableName = "userList";
$countSQL = "select count(*) from $tableName";
$recordGet->setSQL($countSQL);
$result = $recordGet->runSQL();
print_r($result);
?>
Can you help me identify the problem?
EDIT: Actually I haven't got a specific error message. I have an HTTP Error 500 which usually means my code is duff, and I narrowed it down by commenting sections of code until I found the line that caused it.
You have an extra close-paren on line 64.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
The line should be:
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC);