Calling a function of a class does not work php - php

I have a php file called "purchases.controller.php" in which within a function called 'ctrCash' of the 'Purchases' class, I pass variables to a function called 'ctrNewCashPurchase' of the 'CartController' class that I have defined, but when I run the project, I get the message:
"Fatal error : Uncaught Error: Class 'CartModel' not found in ... "
If I do a var_dump inside the function ctrNewCashPurchase, I realize that I am entering that function, but it tells me that it does not recognize 'CartModel' and I do not understand why.
I share the code of the "purchases.controller.php" file:
class CartController{
static public function ctrNewCashPurchase($datos){
$tabla = "compras";
$respuesta = CartModel::mdlNewCashPurchase($tabla, $datos);
if($respuesta == "ok"){
$tabla = "comentarios";
ModeloUsuarios::mdlIngresoComentarios($tabla, $datos);
}
return $respuesta;
}
}
class Purchases {
public function ctrCash (&$arrayCompleto, &$usuario, &$direccion1, &$direccion2, &$dia, &$hora, &$email, &$telefono, &$sesion){
if(isset($usuario)){
//Here I create an array
for($i = 0; $i < count($arrayCompleto); $i++){
$datos = array("idUsuario"=> $sesion,
"idProducto"=> $arrayCompleto[$i]["idProducto"],
"metodo"=> "Efectivo",
"email"=> $email,
"direccion"=> $direccion1,
"detalleDireccion"=> $direccion2,
"diaEnvio"=> $dia,
"horaEnvio"=> $hora,
"telefono"=> $telefono,
"pais"=> "ARG");
}
$respuesta = CartController::ctrNewCashPurchase($datos);
}
}
}
I share the code of the "purchases.model.php" file, where I define the CartModel class:
class CartModel{
static public function mdlNewCashPurchase($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_usuario, id_producto, metodo, email, direccion, pais, detalleDireccion, diaEnvio, horaEnvio, telefono) VALUES (:id_usuario, :id_producto, :metodo, :email, :direccion, :pais, :detalleDireccion, :diaEnvio, :horaEnvio, :telefono)");
$stmt->bindParam(":id_usuario", $datos["idUsuario"], PDO::PARAM_INT);
$stmt->bindParam(":id_producto", $datos["idProducto"], PDO::PARAM_INT);
$stmt->bindParam(":metodo", $datos["metodo"], PDO::PARAM_STR);
$stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
$stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR);
$stmt->bindParam(":pais", $datos["pais"], PDO::PARAM_STR);
$stmt->bindParam(":detalleDireccion", $datos["detalleDireccion"], PDO::PARAM_STR);
$stmt->bindParam(":diaEnvio", $datos["diaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":horaEnvio", $datos["horaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_INT);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt->close();
$tmt =null;
}
}
And I add this other file called 'aux.php' in case it influences something in the error that causes me. Here is how to send 'purchases.controller.php' parameters within the 'ctrCash' function
if(isset($_POST['usuario'])){
require ('purchases.controller.php');
$arrayCompleto = json_decode($_POST['arrayCompleto'], true);
$usuario = $_POST['usuario'];
$direccion1 = $_POST['direccion1'];
$direccion2 = $_POST['direccion2'];
$dia = $_POST['dia'];
$hora = $_POST['hora'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$sesion = $_POST['sesion'];
$payments = new Purchases();
$payments -> ctrCash($arrayCompleto, $usuario, $direccion1, $direccion2, $dia, $hora, $email, $telefono, $sesion);
}

Related

Problems entering information in MySQL database

I'm trying to introduce some data info in the DB on production mode but is not working I'm using PDO for the connection to the DB, in my localhost works correctly but in the GoDaddy server isn't.
I'm using MVC, when I submit I send the data by POST and in the controller is like this
when i make a submit i execute this
$Registro = new ControladorUsuarios();
$Registro -> ctrRegistroUsuario();
static public function ctrRegistroUsuario(){
if (isset($_POST["regUsuario"])) {
if (preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ.]+$/', $_POST["regUsuario"]) &&
preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $_POST["regEmail"]) &&
preg_match('/^[a-z0-9][a-z0-9.]+$/', $_POST["regPassword"])) {
$encriptar = crypt($_POST["regPassword"], '//hash');
$encriptarEmail = md5($_POST["regEmail"]);
$datos = array(
"usuario" => strtolower($_POST["regUsuario"]),
"email" => strtolower($_POST["regEmail"]),
"password" => $encriptar,
"nombre" => strtolower($_POST["regNombre"]),
"apellidos" => strtolower($_POST["regApellido"]),
"telefono" => $_POST["regTelefono"],
"verificacion" => $encriptarEmail
);
$tabla = "usuario";
$respuesta = ModeloUsuarios::mdlRegistroUsuario($tabla, $datos);
if ($respuesta == "ok") {
/*===================================================================
= HERE I SEND A CONFIRMATION MAIL ACCOUNT =
===================================================================*/
$envio = $mail->Send();
if (!$envio) {
echo'error';
} else {
echo 'success';
}
}else{
echo 'error2';
}
}
}
}
when i make a submit the error goes to error2 and in my model i have this
public static function mdlRegistroUsuario($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (usuario, email, password, nombre, apellidos, telefono, verificacion) VALUES (:usuario, :email, :password, :nombre, :apellidos, :telefono, :verificacion)");
$stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR);
$stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
$stmt->bindParam(":password", $datos["password"], PDO::PARAM_STR);
$stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR);
$stmt->bindParam(":apellidos", $datos["apellidos"], PDO::PARAM_STR);
$stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR);
$stmt->bindParam(":verificacion", $datos["verificacion"], PDO::PARAM_STR);
if ($stmt->execute()) {
return "ok";
} else {
return errorinfo();
}
$stmt->close();
$stmt = null;
}
In my error_log appears this errors
#0 route/Controladores/usuarios.controlador.php(33): ModeloUsuarios::mdlRegistroUsuario('usuario', Array)
#1 route/registro.php(42): ControladorUsuarios::ctrRegistroUsuario()
#5 {main}
thrown in route/Modelos/usuarios.modelo.php on line 31
I really don't know what the problem is hope someone can help me

How I can fix "Cannot redeclare" error in PHP?

When the language string is "en" I get this error:
Fatal error: Cannot redeclare getSetting() (previously declared in /Users/manuel/Sites/WebApply/datamanager.php:2) in /Users/manuel/Sites/WebApply/datamanager.php on line 10
I have already tried to change the require imports to require_once but without success.
index.php
if(!file_exists("mysql.php")){
header("Location: setup/index.php");
exit;
}
require_once("datamanager.php");
require_once('assets/languages/lang_'.getSetting("lang").'.php');
datamanager.php
<?php
function getSetting($setting){
require_once("mysql.php");
$stmt = $mysql->prepare("SELECT * FROM settings WHERE NAME = :setting");
$stmt->bindParam(":setting", $setting, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch()) {
return $row["VALUE"];
}
}
function setSetting($setting, $value){
require_once("mysql.php");
$stmt = $mysql->prepare("UPDATE settings SET VALUE = :value WHERE NAME = :setting");
$stmt->bindParam(":setting", $setting, PDO::PARAM_STR);
$stmt->bindParam(":value", $value, PDO::PARAM_STR);
$stmt->execute();
}
function getRankID($username){
require_once("mysql.php");
$stmt = $mysql->prepare("SELECT * FROM accounts WHERE USERNAME = :user");
$stmt->bindParam(":user", $username, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch()) {
return $row["USERRANK"];
}
}
?>

The PHP file does not find a class, but the class is defined

I have a php file called "purchases.controller.php" in which within a function called 'ctrCash' of the 'Purchases' class, I pass variables to a function called 'ctrNewCashPurchase' of the 'CartController' class that I have defined, but when I run the project, I get the message:
"Fatal error : Uncaught Error: Class 'CartModel' not found in ... "
If I do a var_dump inside the function ctrNewCashPurchase, I realize that I am entering that function, but it tells me that it does not recognize 'CartModel' and I do not understand why.
I share the code of the "purchases.controller.php" file:
class CartController{
static public function ctrNewCashPurchase($datos){
$tabla = "compras";
$respuesta = CartModel::mdlNewCashPurchase($tabla, $datos);
if($respuesta == "ok"){
$tabla = "comentarios";
ModeloUsuarios::mdlIngresoComentarios($tabla, $datos);
}
return $respuesta;
}
}
class Purchases {
public function ctrCash (&$arrayCompleto, &$usuario, &$direccion1, &$direccion2, &$dia, &$hora, &$email, &$telefono, &$sesion){
if(isset($usuario)){
//Here I create an array
for($i = 0; $i < count($arrayCompleto); $i++){
$datos = array("idUsuario"=> $sesion,
"idProducto"=> $arrayCompleto[$i]["idProducto"],
"metodo"=> "Efectivo",
"email"=> $email,
"direccion"=> $direccion1,
"detalleDireccion"=> $direccion2,
"diaEnvio"=> $dia,
"horaEnvio"=> $hora,
"telefono"=> $telefono,
"pais"=> "ARG");
}
$respuesta = CartController::ctrNewCashPurchase($datos);
}
}
}
I share the code of the "purchases.model.php" file, where I define the CartModel class:
class CartModel{
static public function mdlNewCashPurchase($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_usuario, id_producto, metodo, email, direccion, pais, detalleDireccion, diaEnvio, horaEnvio, telefono) VALUES (:id_usuario, :id_producto, :metodo, :email, :direccion, :pais, :detalleDireccion, :diaEnvio, :horaEnvio, :telefono)");
$stmt->bindParam(":id_usuario", $datos["idUsuario"], PDO::PARAM_INT);
$stmt->bindParam(":id_producto", $datos["idProducto"], PDO::PARAM_INT);
$stmt->bindParam(":metodo", $datos["metodo"], PDO::PARAM_STR);
$stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
$stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR);
$stmt->bindParam(":pais", $datos["pais"], PDO::PARAM_STR);
$stmt->bindParam(":detalleDireccion", $datos["detalleDireccion"], PDO::PARAM_STR);
$stmt->bindParam(":diaEnvio", $datos["diaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":horaEnvio", $datos["horaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_INT);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt->close();
$tmt =null;
}
}
And I add this other file called 'aux.php' in case it influences something in the error that causes me. Here is how to send 'purchases.controller.php' parameters within the 'ctrCash' function
if(isset($_POST['usuario'])){
require ('purchases.controller.php');
$arrayCompleto = json_decode($_POST['arrayCompleto'], true);
$usuario = $_POST['usuario'];
$direccion1 = $_POST['direccion1'];
$direccion2 = $_POST['direccion2'];
$dia = $_POST['dia'];
$hora = $_POST['hora'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$sesion = $_POST['sesion'];
$payments = new Purchases();
$payments -> ctrCash($arrayCompleto, $usuario, $direccion1, $direccion2, $dia, $hora, $email, $telefono, $sesion);
}
The error is beacause the model is not imported for the controller.
You can include it in the controller, it's the same (in this case).
if(isset($_POST['usuario'])){
require_once ('purchases.model.php');
require_once ('purchases.controller.php');
...
}

When I run the PDO script alone it work fine but when I put it in a function it will not work

When I run the PDO script alone it runs just fine But when I run it in a function I get this error Fatal error: Call to a member function prepare() on a non-object. I can not figure out why it is happening.
$pid = 6;
$custid = 1;
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
$pid = 6;
$custid = 1;
function test($custid,$pid){
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
}
echo test($custid,$pid);
The variable $db is not visible inside your function. you need to add
function test($custid,$pid){
global $db;
[...]
}
inside your function or you should pass the db object to your function via parameter:
function test($db, $custid,$pid){
[...]
}
another nice way ist to work with the factory patterns:
create a class db with a static method dbFactory and call it whenever you need to access your db
class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');

INSERT query does not work, empty array?

<?php
class Worker extends Core {
public $name;
public $surname;
public $dob;
public $skills;
public $postcode;
public $street;
public $email;
public $tel;
public $ern;
public $result;
public function __construct () {
$this->name = 'name';
$this->surname = 'surname';
$this->dob = 'dob';
$this->skills = 'skills';
$this->postcode = 'postcode';
$this->street = 'street';
$this->email = 'email';
$this->tel = 'tel';
$this->ern = 'ern';
}
//Saving worker data to database, need provide group name (table name)
public function saveWorker($group) {
if(!(isset($this->conn))) parent::__construct();
try
{
$this->conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //catch exceptions
$q = 'INSERT INTO :group (name, surname, dob, skills, postcode, street, email, tel, erefnumber) VALUES (
:name,
:surname,
:dob,
:skills,
:postcode,
:street,
:email,
:tel,
:erefnumber)'; //sql query with group name
$stmt = $this->conn->prepare($q);
$stmt -> bindValue(':group', $group, PDO::PARAM_STR);
$stmt -> bindValue(':name', $this->name, PDO::PARAM_STR);
$stmt -> bindValue(':surname', $this->surname, PDO::PARAM_STR);
$stmt -> bindValue(':dob', $this->dob, PDO::PARAM_STR);
$stmt -> bindValue(':skills', $this->skills, PDO::PARAM_STR);
$stmt -> bindValue(':postcode', $this->postcode, PDO::PARAM_STR);
$stmt -> bindValue(':street', $this->street, PDO::PARAM_STR);
$stmt -> bindValue(':email', $this->email, PDO::PARAM_STR);
$stmt -> bindValue(':tel', $this->tel, PDO::PARAM_STR);
$stmt -> bindValue(':erefnumber', $this->erefnumber, PDO::PARAM_STR);
$results = $stmt->execute();
if($results > 0)
{
return 'Dodano: '.$ilosc.' rekordow';
}
else
{
return 'Wystapil blad podczas dodawania rekordow!';
}
}
catch(PDOException $e)
{
return 'There was some error: ' . $e->getMessage();
}
unset($stmt);
}
//no exceptions
public function getWorker()
{
$workerData = array (
"name" => $this->name,
"surname" => $this->surname,
"dob" => $this->dob,
"skills" => $this->skills,
"postcode" => $this->postcode,
"street" => $this->street,
"email" => $this->email,
"tel" => $this->tel,
"tel" => $this->erefnumber
);
return $workerData;
} // end getWorker();
public function searchWorker($name, $surname, $dob, $skills, $postcode, $street, $email, $tel, $erefnumber) {
}
function deleteWorker() {
}
function getEmployer() {}
public function __sleep () {
parent::__sleep();
}
} // end Person;
//DB connection
class Core {
public $conn;
public function __construct() {
$this->dbConnect();
}
public function dbConnect() {
$host = 'localhost';
$port = '3307';
$username = 'modium_test';
$password = 'test';
$database ='modium_test';
try{
$this->conn = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
echo 'Connection successful!';
echo var_dump($this->conn);
}
catch(PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
public function __sleep () {
unset($this->conn);
}
}
}
The query just doesn't work. Every previous function worked, but when I try to INSERT tables via sql query, nothing happends.
Worker is an object it's created well, then i get some POST array assigned to it, wich also works fine then i try to saveWorker but it gives nothing.
The invoking line:
var_dump($worker);
if (isset($worker)) echo 'worker is set';
if (isset($worker->conn)) echo 'thers connection is set';
$worker->saveWorker('workers');
With added lines:
echo "\nPDO::errorInfo():\n";
print_r($stmt->errorInfo());
print_r($this->conn->errorInfo());
echo "end of error info";
It gives me:
PDO::errorInfo():
Array ( [0] => ) Array ( [0] => 00000 )
end of error info
$stmt->execute() returns a boolean value (Manual). Try,
$results = $stmt->execute();
if($results !== FALSE) {
return 'Dodano: '.$ilosc.' rekordow';
} else {
return 'Wystapil blad podczas dodawania rekordow!';
}
Also, you cannot bind tablename.

Categories