I wonder whats the problem in my code? I tried all the sources I can search but it still gives me the same error which is still "Call to a member function bind_Param() on a non-object".here's my code.,hope someone can help me, thanks
$app->get('/students/:student_id',function () use($app){
$sql = "SELECT * FROM students WHERE student_id =:student_id";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("student_id", $student_id);
$stmt->execute();
$students = $stmt->fetchObject();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
This one works:
$app->get('/students/:student_id', function ($student_id) use($app){
$sql = "SELECT * FROM students WHERE student_id = ?";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$students = $result->fetch_object();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
I assume that you're using this definition of the connect_db function:
function connect_db() {
$dbhost="localhost";
$dbuser="user";
$dbpass="pass";
$dbname="stackoverflow-33750846";
return new mysqli($dbhost, $dbuser, $dbpass, $dbname);;
}
Perhaps there is a bit of confusion using the database connection and read data from it, so I add some points:
Be sure to pass $student_id as a parameter to the callable function;
$stmt->bind_Param accepts a string that represents the type of the parameters and all the binding parameters;
fetchObject is a function of the mysqli_result class.
Related
i have a PHP REST API, i did this function to get services with a certain idpro or idclient
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:idpro OR idclient= :idclient ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("idpro", $id);
$stmt->bindParam("idclient", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I have in my database a row with idpro=40 and idclient=30 when i execute this function with id=40 in get the disered result but when i execute it with id=30 i dont get anything, i tried to execute this line in PHPMYADMIN: select * FROM service WHERE idpro=30 OR idclient= 30 and it worked as expected
$sql = "select * FROM service WHERE idpro=:idpro OR idclient=:idclient ORDER BY date_debut DESC";
You mentioned that it worked with idpro and it has no space between the parameter and value so try and remove the space between idclient= :idclient to see if thats the issue. Since it works when you execute the line I assume that its how it is syntactically called.
OR
Try using one parameter for the value. Change like this:
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:myID OR idclient= :myID ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("myID", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I'm having a little bit of an issue with PDO binding Parameters.
My setup is as follows.
Ubuntu Desktop 16.04
Netbeans 8.1 (php and html only version)
php cli 7.0.4 (Running internal web server)
Postgres SQL 9.5
Slim Framework 3
I have opted to use PDO to access my database. This is my learning the system for a future project.
I can grab all records from a table, I can get the argument issued in the uri to echo on screen.
But using the GET method to locate a specific entry throws the following error at me.
{"error":{"text":SQLSTATE[08P01]: <>: 7 ERROR: bind message supplies 0 parameters, but prepared statement "pdo_stmt_00000001" requires 1}}
The following is my code.
db.php
<?php
function getDB() {
$dbtype="pgsql";
$dbhost="localhost";
$dbuser="postgres";
$dbpass="SomeSecurePassword";
$dbname="bms";
$dbConnection = new PDO("$dbtype:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>
index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
require 'db.php';
$app = new \Slim\App;
$app->get('/','getRoot');
$app->get('/contacts', 'getContacts');
$app->get('/contacts/{contact_id}', 'getContact');
$app->run();
function getRoot() {
echo 'This is the Root URI';
}
function getContacts() {
$sql = "SELECT last_name,first_name FROM contacts ORDER BY last_name DESC";
try {
$db = getDB();
$stmt = $db->query($sql);
$contacts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"Contacts": ' . json_encode($contacts) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getContact(Request $request, Response $response, $args) {
$contact_id = (int)$args['contact_id'];
$sql = "SELECT * FROM contacts WHERE contact_id = :contact_id";
try {
$db = getDB();
$stmt = $db->query($sql);
$stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$stmt->execute();
$stmt->debugDumpParams();
$db = null;
echo '{"Contact": ' . json_encode($contact) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Where could I be going wrong?
You need to use prepared statements.
$stmt = $db->query($sql); //Executes a query and returns a statement
What you want is...
$stmt = $db->prepare($sql);
$stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$stmt->execute();
So I have this code
$lang=new language();
$default_language=$lang->getLanguage(0);
$currencies = new currency();
$currencies = $currencies->getCurrencies();
getCurrencies() and getLanguage() are in another file with classes.
public function getCurrencies() {
$curr=new record();
return $curr -> getRecords('currencyTable','currency_order',array("currency_id","currency_name"));
}
public function getLanguage($record) {
$lang=new record();
return $lang->getRecord('languageTable',$record,'lang_order','*');
}
And getRecords and getRecord are public functions it the record class
I keep on getting the error
Fatal error: Call to a member function prepare() on null
Referring to the query of the getRecords functions.
I dont know how to fix this. Does this has to do with the connection to the database?
Also, the weird part is that if I remove the
$lang=new language();
$default_language=$lang->getLanguage(0);
part, this error goes away. Any help? Is the error in the $default_language=$lang->getLanguage(0); line and this is why it is messing up the database connection, resulting to this error?
Thanks
EDIT
Here are the getRecord and getRecords
public function getRecords($table,$sorder,$field_names) {
$conn = db::open();
//- build string of field names
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//end up with field1, field2... or *
//soreder is a field, contains int like 1 2 3
//- run statement
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
and
public function getRecord($table,$record,$sorder,$field_names) {
$conn = db::open();
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//same things for $field_string and $sorder
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." LIMIT ? OFFSET ?");
$stmt->bindValue(1, 1 , PDO::PARAM_INT);
$stmt->bindValue(2, $record, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
}
I fixed an error. In getRecord I had LIMIT 1 and I fixed it as above. I still get the same error about the getRecords line : $stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
Any thoughts?
Thanks
Your database connection failed. The error is not in your posted code. The error in your code is when the statement is being prepared.
Ex: $statement = $dbh->prepare("SELECT * FROM some_table"). I would recommend throwing an exception to see what's going wrong with your connection. You can do this by adding the options to your pdo initialization. array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
try{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB,
MYSQL_USERNAME,
MYSQL_PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(Exception $e){
echo $e->getMessage();
}
Hope this helps
I created a REST API and I've come to the point where I want to output 20 rows (e.g.) if I access the API like http://api.randomuser.me/?results=20.
This is my PHP code. I am new to Slim and AngularJS, please help.
function getUsers() {
$sql = "select * FROM user";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Thanks in advance.
You will have to change your sql... something like
$limit = $_GET['limit'];
/clean your input make sure it has a value using isset,empty etc
$sql = "select * FROM user ORDER BY id LIMIT ".$limit; //this is a quick example rather use pdo bound parameters.
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Remember to clean your input and use bound parameters in your query.
Read the results parameter in a variable, and use it in the LIMIT clause instead of the hard coded 10
function getUsers() {
try {
$db = getConnection();
$limit = $_GET["results"];
// validate $limit for valid value here and continue only if
// using something like
// $limit = $db->real_escape_string($limit);
// and continue only if successfully validated
$sql = "select * FROM user ORDER BY id LIMIT ".(strlen($limit) ? $limit : 10);
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I am using PDO for the first time. I created this method, and I am getting this error:
Call to a member function rowCount() on a non-object
The following is my code.
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpassword)
function doesRecordExist($query) {
global $db;
try {
$stmt = $db->query($query);
$count = $stmt->rowCount();
return $count;
} catch (PDOException $ex) {
die($ex->getMessage());
}
}
Can you help me please
Why not use prepared statements: Plus you need to execute you query before you count it
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpassword)
function doesRecordExist($query) {
global $db;
try {
$stmt = $db->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
return $count;
} catch (PDOException $ex) {
die($ex->getMessage());
}
}
Don't use a global variable. Pass this one as an object instead.
$db = new PDO(....);
function doesRecordExist($query, PDO $db) {
try {
$stmt = $db->prepare($query);
$stmt->execute();
...
I forgot to create a table that the query was referring to. Sorry for any inconveniences