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();
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 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.
I have trouble deleting record from my MYSQL Database(with Slim PHP framework). My code is:
PHP
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->delete('/delete_article', 'deleteArticle');
$app->run();
function deleteArticle() {
$request = Slim::getInstance()->request();
$article = json_decode($request->getBody());
$sql = "DELETE FROM articles WHERE article_name = ':article_name'";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("article_name", $article->name);
$stmt->execute();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Template controller:
'use strict';
app.controller('clankyCtrl', ['$scope', '$http', '$location',
function ($scope, $http, $location) {
$scope.delete_article = function(article) {
$http.delete('data/api/delete_article', article).success(function(){
$location.path('home/clanky');
});
};
}]);
Template:
<tr ng-repeat="article in articles">
<td>{{article.article_name}}</td>
<td ng-bind-html="article.article_content | cut:true:100"></td>
<td class="text-right">{{article.article_datetime}}</td>
<td>edit/<button ng-click="delete_article(article)">Delete</button></td>
</tr>
Since HTTP response is 200 I suppose the mistake is probably in data selection.
You don't need quotation marks around :article_name in your query. PDO bindParam takes care of this for you. You also need to colon in front of the name when binding. Try this:
$sql = "DELETE FROM articles WHERE article_name = :article_name";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":article_name", $article->name);
$stmt->bindParam(":article_name", $article->name);
i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>
I'm trying to convert my codes to PDO from mysql_query, and starting with this function
function label_for_field($field_name, $table_name) {
$table = array();
// Bind variables to parameters
$param_array = array(':bundle' => $table_name, ':field_name' => $field_name);
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
// Execute
$STH -> execute($param_array);
// Set the fetch mode
$STH -> setFetchMode(PDO::FETCH_OBJ);
while ($row = $STH -> fetch()) {
$info = unserialize($row -> data);
$table[] = $info['label'];
}
return $table[0];
}
and I'm trying out just output it to see if it works
include_once ("includes/connect.php");
include ("includes/functions.php");
echo label_for_field("field_account_number", "account_table");
And here's the connect.php
// Include Constants
require_once ("constants.php");
//Establish Connection
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch (PDOException $e) {
echo $e -> getMessage();
}
I don't know if it's because I'm binding the parameters wrong, it just gave me an server error page
"Server error. The website encountered an error while retrieving ......."
Thanks in advance
You need to set the PDO error mode to produce exceptions before you can catch them.
In your connect.php:
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Then you can have a similar try/catch statement in your function to that of your connection file, and use it to show the error in your development environment.
Try this instead to see if you get valid objects returned from the query.
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
$STH->bindValue(":bundle", $table_name);
$STH->bindValue(":field_name", $field_name);
$STH->execute();
$STH->setFetchMode (PDO::FETCH_OBJ);
$result = $STH->fetchAll();
var_dump($result);