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);
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();
i am trying to create a service that will return a json data from php api, but instead of return pure json data, the angular seem to return JSON together with its config.
services.js
.service('DistinctAPIService', function($http){
var base = 'http://localhost/onseral/api/';
this.listDistinct = function(table, field){
return $http({
method: 'POST',
url: base + '/listDistinct.php',
params: {
table: table,
field: field
}
});
}
})
.controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(data){
$scope.data = data;
console.log(JSON.stringify(data));
})
})
listdistinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
instead of returning the correct JSON data, it returned
{"data":{"data":[{"expr1":"CFFBPS16"}]},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/onseral/api//listDistinct.php","params":{"table":"material_copy","field":"matcode"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
any idea?
try this
controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(response){
$scope.data = response.data.data;
console.log(JSON.stringify(data));
})
Use header function before sending data to the client side.
i modified your listdistinct.php file. try it , let me know if issue persist.
<?php $sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
header('Content-Type: application/json');
echo json_encode(array('data' => $data));
} 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.
unable to delete i row using PDO in php. Here is my code given below
this is inc.common.php
<?php
#session_start();
include_once '../common/inc.config.php';
include_once '../common/inc.globalConstants.php';
$db = new PDO("mysql:host=$mdbhost;dbname=$mdbname",$mdbuser,$mdbpass );
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
include_once '../classes/cls.common.php';
$Cobj=new common($db);
?>
this my cls.class.php
<?php
class common {
public function common($dbcon) {
$this->dbCon = $dbcon;
}
public function getCustomData($tableName,$fields, $conditions = "") {
$stmt = "";
$sql = "";
$sql = "SELECT $fields FROM $tableName $conditions ";
$stmt = $this->dbCon->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$count = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
?>
this is my addinfo.php
<?php
include '../common/inc.common.php';
$class_id=$_POST['refid'];
if(isset($_POST['mode']))
{
$tableName="class";
$class_id=$_POST['refid'];
$res=$Cobj->delet($tableName, $class_id);
}
?>
on passing variables using AJAX call i couldn't able to delete the row .Ajax call is success . only problem with PDO delete.
$.ajax({
url: "../masters/addinfo.php",
type: "POST",
data:"refid="+class_id+"&mode=delete",
});
my class table has 4 fields classId,name,date,stat.
The $stmt variable in function delet() is not defined.
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$stmt = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
Will fix this. Note what changed; $count changed to $stmt