I have been looking at several php codes trying to find out the problem with my code, and why it wont receive data from post
below is my php code can any one tell me whats up with it
i am trying to send audio data with the name of the audio file through this php file
the php script is supposed to receive the audio file create then audio object and then extract the name and audio part from the file but when i send the data to test it through postman i get 400 error message as i have set it up to indicate error but i do not understand why this is happening
<?php
include_once '../../configration/database.php';
include_once '../../objects/sound.php';
// JWT TOKEN VALIDATION
$data = json_decode(file_get_contents("php://input"));
$database = new Database();
$conn = $database->getConnection();
// CONTROL
$sound = new Sound($conn);
// make sure data is not empty
if (
!is_null($data->$filename)
&& !is_null($data->$extension)
&& !is_null($data->$waveform) )
{
$sound->filename = $data->filename;
$sound->extension = $data->extension;
$sound->waveform = $data->waveform;
// create the product
if ($sound->create_new())
{
http_response_code(200);
}
else
{
http_response_code(503);
echo json_encode(array(
"message" => "Unable to create sound."
));
}
}
else {
http_response_code(400);
echo json_encode(array(
"message" => "Unable to create sound. Data is incomplete."
));
}
?>
the database.php file is as follows
<?php
include_once 'GlobalConfig.php';
class Database
{
public $conn;
public function getConnection(){
$config= new GlobalConfig();
$this->conn = null;
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
public function getConnectionAndValidate($data){
$this->conn = null;
$config= new GlobalConfig();
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
if (!validateToken($data->JWT, $data->UserID, $this->conn)){
http_response_code(401);
echo "Authorization: declined";
exit();
}
return $this->conn;
}
}
THE sound.php FILE IS AS FOLLOWS
<?php
class Sound
{
private $conn;
private $table_name = "";
public $filename;
public $extension;
public $waveform;
public $path;
public function __construct($db)
{
$this->conn = $db;
}
function create_new()
{
$this->path = $this->filename .".". $this->extension;
$myfile = fopen($this->path, "w") or die("Unable to open file!");
fwrite($myfile, $this->waveform);
fclose($myfile);
// $query = " INSERT INTO `tbl_address`
// (`contact_number`,`UserID` ,`billing_street_address`, `billing_city_address`, `billing_state_address`, `billing_country_address`, `billing_zip`,
// `shipping_street_address`, `shipping_city_address`, `shipping_state_address`, `shipping_country_address`, `shipping_zip`)
// VALUES (:contact_number,'$this->user_id', :billing_street_address, :billing_city_address, :billing_state_address, :billing_country_address, :billing_zip,
// :shipping_street_address, :shipping_city_address, :shipping_state_address, :shipping_country_address, :shipping_zip);";
// $stmt = $this->conn->prepare($query);
// $this->contact_number = htmlspecialchars(strip_tags($this->contact_number));
// $this->billing_street_address = htmlspecialchars(strip_tags($this->billing_street_address));
// $this->billing_city_address = htmlspecialchars(strip_tags($this->billing_city_address));
// $this->billing_state_address = htmlspecialchars(strip_tags($this->billing_state_address));
// $this->billing_country_address = htmlspecialchars(strip_tags($this->billing_country_address));
// $this->billing_zip = htmlspecialchars(strip_tags($this->billing_zip));
// $this->shipping_street_address = htmlspecialchars(strip_tags($this->shipping_street_address));
// $this->shipping_city_address = htmlspecialchars(strip_tags($this->shipping_city_address));
// $this->shipping_state_address = htmlspecialchars(strip_tags($this->shipping_state_address));
// $this->shipping_country_address = htmlspecialchars(strip_tags($this->shipping_country_address));
// $this->shipping_zip = htmlspecialchars(strip_tags($this->shipping_zip));
// // bind values
// $stmt->bindParam(":contact_number", $this->contact_number);
// $stmt->bindParam(":billing_street_address", $this->billing_street_address);
// $stmt->bindParam(":billing_city_address", $this->billing_city_address);
// $stmt->bindParam(":billing_state_address", $this->billing_state_address);
// $stmt->bindParam(":billing_country_address", $this->billing_country_address);
// $stmt->bindParam(":billing_zip", $this->billing_zip);
// $stmt->bindParam(":shipping_street_address", $this->shipping_street_address);
// $stmt->bindParam(":shipping_city_address", $this->shipping_city_address);
// $stmt->bindParam(":shipping_state_address", $this->shipping_state_address);
// $stmt->bindParam(":shipping_country_address", $this->shipping_country_address);
// $stmt->bindParam(":shipping_zip", $this->shipping_zip);
// if ($stmt->execute()) {
// $this->address_id = $this->conn->lastInsertId();
// }
// else {
// echo json_encode(array("message" => "Unable to get address."));
// }
}
}
?>
Related
I got an error when I want to consume a Rest API using postaman and docker.
The error is marked in this line of code: Error in php Connection Error: could not find driver
<?php
class Materias {
// DB stuff
private $conn;
private $table = 'materias';
// Materias Properties
public $clave_materia;
public $nombre_materia;
public $semestre;
public $creditos;
// Constructor with DB
public function __construct($db) {
$this->conn = $db;
}
// Get Materias
public function read() {
// Create query
$query = 'SELECT * FROM ' . $this->table;
// Prepare statement
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
}
// Get Single Materia
public function read_single() {
// Create query
$query = 'SELECT * FROM ' . $this->table . 'WHERE clave_materia = ?';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Bind clave_materia
$stmt->bindParam(1, $this->clave_materia);
// Execute query
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Set properties
$this->nombre_materia = $row['nombre_materia'];
$this->semestre = $row['semestre'];
$this->creditos = $row['creditos'];
}
// Create Post
public function create() {
// Create query
$query = 'INSERT INTO ' . $this->table . ' SET clave_materia = :clave_materia, nombre_materia = :nombre_materia, semestre = :semestre, creditos = :creditos';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
$this->nombre_materia = htmlspecialchars(strip_tags($this->nombre_materia));
$this->semestre = htmlspecialchars(strip_tags($this->semestre));
$this->creditos = htmlspecialchars(strip_tags($this->creditos));
// Bind data
$stmt->bindParam(':clave_materia', $this->clave_materia);
$stmt->bindParam(':nombre_materia', $this->nombre_materia);
$stmt->bindParam(':semestre', $this->semestre);
$stmt->bindParam(':creditos', $this->creditos);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Update Post
public function update() {
// Create query
$query = 'UPDATE ' . $this->table . '
SET nombre_materia = :nombre_materia, semestre = :semestre, creditos = :creditos
WHERE clave_materia = :clave_materia';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->nombre_materia = htmlspecialchars(strip_tags($this->nombre_materia));
$this->semestre = htmlspecialchars(strip_tags($this->semestre));
$this->creditos = htmlspecialchars(strip_tags($this->creditos));
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
// Bind data
$stmt->bindValue(':nombre_materia', $this->nombre_materia);
$stmt->bindValue(':semestre', $this->semestre);
$stmt->bindValue(':creditos', $this->creditos);
$stmt->bindValue(':clave_materia', $this->clave_materia);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Delete Post
public function delete() {
// Create query
$query = 'DELETE FROM ' . $this->table . ' WHERE clave_materia = :clave_materia';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->clave_materia = htmlspecialchars(strip_tags($this->clave_materia));
// Bind data
$stmt->bindParam(':clave_materia', $this->clave_materia);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
}
Error:
Connection Error: could not find driver<br />
<b>Fatal error</b>: Uncaught Error: Call to a member function prepare() on null in /var/www/html/models/Materias.php: 24
Stack trace:
#0 /var/www/html/api/materias/read.php(17): Materias->read()
#1 {main
}
thrown in <b>/var/www/html/models/Materias.php</b> on line <b>24</b><br />
**bd connection**
<?php
class Database {
// DB Params
private $host = 'localhost';
private $db_name = 'reticula';
private $username = 'root';
private $password = 'test ';
private $conn;
// DB Connect
public function connect() {
$this->conn = null;
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
return $this->conn;
}
}
This is where you call matters
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Materias.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate blog post object
$materias = new Materias($db);
// Blog post query
$result = $materias->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if($num > 0) {
// Post array
$materias_arr = array();
// $posts_arr['data'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$materias_item = array(
'clave_materia' => $clave_materia,
'nombre_materia' => $nombre_materia,
'semestre' => $semestre,
'creditos' => $creditos
);
// Push to "data"
array_push($materias_arr, $materias_item);
// array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($materias_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
Working on a product adding page using PHP OOP and mysqli, at this point i'm working on prepared statement implementation but can't find information on how to add them into such code.
Any guidlines will be apreciated.
Code:
DB connection class:
<?php
class DbConfig {
private $_host = 'localhost';
private $_username = 'root';
private $_password = 'falcons17';
private $_database = 'scandiweb';
protected $connection;
public function __construct()
{
if (!isset($this->connection)) {
$this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
if (!$this->connection) {
echo 'Cannot connect to database server';
exit;
}
}
return $this->connection;
}
}
?>
Execute function:
public function execute($query) {
$result = $this->connection->query($query);
if ($result == false) {
echo mysqli_error($this->connection); /*'Error: cannot execute the command'*/
return false;
} else {
return true;
}
}
Validating and adding procedure :
<?php
//including the database connection file
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$sku = $crud->prepare_string($_POST['sku']);
$name = $crud->prepare_string($_POST['name']);
$price = $crud->prepare_string($_POST['price']);
$products = $crud->prepare_string($_POST['products']);
$weight = $crud->prepare_string($_POST['weight']);
$capacity = $crud->prepare_string($_POST['capacity']);
$height = $crud->prepare_string($_POST['height']);
$width = $crud->prepare_string($_POST['width']);
$length = $crud->prepare_string($_POST['length']);
$check_int = $validation->is_int($_POST, array('price','weight','capacity','height','width','length'));
if ($check_int != null){
echo $check_int;
}else {
$result = $crud->execute("INSERT INTO products(sku,name,price,product_type,weight,capacity,height,width,length) VALUES('$sku','$name','$price','$products','$weight','$capacity','$height','$width','$length')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
Here is a class i often use. It gets the login from a separate .ini-file. Feel free to change for your needs. Keep in mind that it sets associative arrays as standard.
class CC_DBV {
private static $mysqlhost;
private static $mysqluser;
private static $mysqlpwd;
public static $mysqldb;
private static $db;
private static $mysqlport;
function __construct() {
// ini File einlesen
$globSettings = parse_ini_file(_ROOTV_.'cfg/main.ini',true);
// Datenbankverbindung
self::$mysqlhost = $globSettings ['db_settings']['host']; // MySQL-Host aus Config Datei
self::$mysqluser = $globSettings ['db_settings']['db_user']; // MySQL-User aus Config Datei
self::$mysqlpwd = $globSettings ['db_settings']['db_pswd']; // Passwort aus Config Datei
self::$mysqldb = $globSettings ['db_settings']['db']; // Datenbank aus Config Datei
self::$mysqlport = $globSettings ['db_settings']['port']; // Datenbank aus Config Datei
}
public function getInstance( ) {
if(!self::$db) {
try{
self::$db = new \PDO(
'mysql:host='.self::$mysqlhost.';dbname='.self::$mysqldb.';port='.self::$mysqlport,
self::$mysqluser,
self::$mysqlpwd,
array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
)
);
//self::$db->exec("SET NAMES utf8");
return self::$db;
}catch (\PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}else{
return self::$db;
}
}
}
To use it you do something like this:
$conn = new CC_DBV(); // you can use this connection multiple times, it's persistant.
$inst = $conn->getInstance(); // create or get the instance of the opened connection
$stmnt = $inst->prepare("SELECT * FROM tablename WHERE xyz = :VAR1"); // prepare statement with placeholder(s)
$v = array(':VAR1' => 'aValue'); // set up an array with corresponding values
$r1 = $stmnt->execute($v); // execute statement with values
if(!$r1){ echo "PANICMODE";}else{ var_dump($stmnt->fetchAll()));
I got stuck for hours in the code below. I don't know how I can fix this error.
Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\code\abc\Services\Backend.php:16 Stack trace: #0 C:\xampp\htdocs\code\abc\v1\Api.php(9): Backend->userLogin() #1 {main} thrown in C:\xampp\htdocs\code\abc\Services\Backend.php on line 16.
DB.php file
<?php
$Servername = "localhost";
$Username = "root";
$Password = "";
$dbName = "android";
// multi
$conn = new mysqli($Servername, $Username, $Password, $dbName);
?>
Service.php file
<?php
//Class Services
class Services
{
//Variable to store database link
public $conn;
//Class constructor
function __construct()
{
$this->connect();
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/linkDB.php';
// //Checking if any error occured while connecting
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->mysqli_connect_error();
}
//finally returning the connection link
return $this->conn;
}
}
?>
Backend.php file
<?php
/**
* to perform all the operation needed
*/
class Backend extends Services
{
function __construct()
{
parent::__construct();
}
# always login the user in [WHERE user_id='{$id}' AND password='{$password}'] [$id , $password]
public function userLogin()
{
$stmt = "SELECT * FROM heroes ";
$retval = $this->conn->query($stmt);
$data = $retval->fetch_array();
$row = $retval->num_rows;
if ($row == 1) {
return true;
} else {
return false;
}
print_r($this->conn);
}
# register a new lecturer or student[$id , $phone , $email , $type, $password , $rpassword]
// public function userRegister($name, $realname, $rating, $teamaffiliation)
// {
// $stmt = "INSERT INTO heroes(name, realname, rating, teamaffiliation)
// VALUES('{$name}', '{$realname}', '{$rating}', '{$teamaffiliation}')";
// $retval = $this->conn->query($stmt);
// // $retval = mysqli_query($this->conn , $stmt);
// var_dump($this->conn);
// if($retval){
// return true;
// }else {
// return false;
// }
//
// }
# make a new order
// public function accReset($id, $email){
// $stmt = "UPDATE users_tbl SET username='{$user}' AND user_password='{$pass}' WHERE user_id={$uid}";
// $retval = $this->conn->query($stmt);
// if($retval)
// return true;
// return false;
// }
//
// # know your order history
// public function OrderHistory($id)
// {
// # code...
// }
//
// # hlogout the user now...
// public function Logout()
// {
// session_start();
// session_unset();
// session_destroy();
// }
//
// public function hash($password)
// {
//
// }
}
?>
LinkDB.php file
<?php require_once '../../startups/DB.php'; ?>
Api.php file
<?php
require_once '../Services/Services.php';
require_once '../Services/Backend.php';
// $api = new Services;
$api = new Backend;
// $api->userRegister('YOUR', 'Killersbeans', '2', 'X-men');
$api->userLogin();
?>
I am pretty new to PHP, I have referred some examples and made a code for getting data from database. but if the database is not found I am getting a text response , Can anyone suggest how to get a proper JSON response back if no database found or misconfigured
This is my $http.get method
$http.get('client/php/popData.php')
.success(function(data) {
$scope.blogs = data;
})
.error(function(err) {
$log.error(err);
})
popdata.php for getting data from database
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$db = new DB();
$data = $db->qryFire();
echo json_encode($data);
?>
This is my config.php
<?php
define("__HOST__", "localhost");
define("__USER__", "username");
define("__PASS__", "password");
define("__BASE__", "databasename");
class DB {
private $con = false;
private $data = array();
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
die("DB connection failed:" . mysqli_connect_error());
}
}
public function qryPop() {
$sql = "SELECT * FROM `base` ORDER BY `id` DESC";
$qry = $this->con->query($sql);
if($qry->num_rows > 0) {
while($row = $qry->fetch_object()) {
$this->data[] = $row;
}
} else {
$this->data[] = null;
}
$this->con->close();
}
public function qryFire($sql=null) {
if($sql == null) {
$this->qryPop();
} else {
$this->con->query($sql);
$this->qryPop();
}
// $this->con->close();
return $this->data;
}
}
?>
Use Exceptions:
Change your class DB like this:
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
Then change your popdata.php like
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
try {
$db = new DB();
$data = $db->qryFire();
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
exit();
}
echo json_encode($data);
This way you will get error response in JSON for any Exception thrown while constructing the DB class and while executing DB::qryFire
if you want to catch your warnings you can try modifying your DB class like the below:
public function __construct() {
ob_start();
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
$warning = ob_clean();
if ($warning) {
throw new Exception($warning);
}
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
You can also turn off your warnings and notices by adding
error_reporting(E_ERROR);
on the top of your file
replace the line die("DB connection failed:" . mysqli_connect_error()); in DB class __construct function with
die( json_encode( array('status' => 'error') ) );
when ever the app will fail to connect to the data base it will give
{"status": "error"}
i did not checked this. but i hope it will work
btw it's my 1st answer on stackoverflow. i'm sorry for my mistakes. correct them
i have problem with function pdo, when it will take 1 record from the database, the result is null;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
and to display
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
database is not empty, but result display
no error, and also does not display anything
If you see correctly on the following line :
$records = $obj->detailitem('product WHERE url = "$url"');
It passes the string as "$url" , not the value of $url variable.
So change it to :
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');