<?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.
Related
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);
}
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');
...
}
I'm trying to update my database but whenever i do like this
if($query){
echo 'executed';
}
else {
echo 'error';
}
The problem I'm facing is that query is successfully updating database but result in false response here is my code
public static function updateItem($slug, $title, $description, $thumbnail, $preview, $main_file, $screenshot, $category, $amount, $review, $demo_url, $tags, $live, $video, $apc) {
$db = new Database;
$main_category = Login::encrypt_decrypt("decrypt", $apc);
$sub_category = Login::encrypt_decrypt("decrypt", $category);
$q = $db->updateRow("UPDATE items SET name = ?, description = ?, thumbnail = ?, main_file = ?, categories = ?, sub_category = ?, demo_url = ?, slug = ?, price = ?, reviewer_comment = ?, datetime = ?, status = ?, video_file = ?, item_tags_string = ?, preview_file = ?, screenshot_file = ?, live_file = ? WHERE user_id = ? AND temp_files != '' AND temp_file_real != '' AND status = ?", [$title, $description, $thumbnail, $main_file, $main_category, $sub_category, $demo_url, $slug, $amount, $review, Item::nowTime(), 'queue', $video, $tags, $preview, $screenshot, $live, Profile::getid(), 'temp']);
if($q){
echo 'good'; exit;
}
else {
echo 'wrong'; exit;
}
}
This is my database connection code
public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
$this->isConn = TRUE;
try {
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
here is update query function
public function updateRow($query, $params = []) {
$this->insertRow($query, $params);
}
public function insertRow($query, $params = []) {
try {
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
can anyone tell me why I'm receiving false statement always
Your updateRow function doesn't return anything so '$q' is empty.
public function updateRow($query, $params = []) {
return $this->insertRow($query, $params);
}
Hi i get a value with post methos and i want to check it with function func_check_seven_userid()
when i use :
$stmt = $this->conn->prepare("SELECT * FROM content where content_id= ".$this->seven);
$stmt->execute();
it work.
but when i use :
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
it is not work!!!
my complet code is :
<?php
class insert_content {
private $conn;
private $seven;
private $row_id;
//**********************************************************************
function connect() {
include 'db_connection.php';
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//************************************************************************
private function func_check_seven_userid() {
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
$row = $stmt->fetch();
$this->row_id = $row[0];
if ($this->row_id) {
echo 'yes';
}
else {
echo 'no';
}
}
//****************************************************************
function __construct($parms) {
$this->connect();
$this->seven = $parms['seven'];
$this->func_check_seven_userid();
}
function __destruct() {
$this->conn = null;
}
}
if (isset($_POST['seven'])) {
$parms = array('seven' => ($_POST['seven']));
$class = new insert_content($parms);
}
?>
thanks for help
I found this:
<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
on http://php.net/manual/en/pdo.prepare.php
Here the statement is prepared with PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY
Maybe it does the difference. Hope it helps
Alright so my problem is simple, Im trying to get results from a query but it always returns that there are no users registered with the username.
<?php
require "assembly/oop/sql_classbuild.php";
class player {
private $name;
private $age;
private $gender;
private $location;
public function createNew($name, $age, $gender, $location) {
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("INSERT INTO players (name, age, gender, location) VALUES (?,?,?,?)");
$stmt->bind_param("siss", $name, $age, $gender, $location);
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->location = $location;
$stmt->execute();
$stmt->close();
$conn->close();
}
public function isRegistered($name) { //problematic code
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("SELECT name FROM players WHERE name=?");
$stmt->bind_param("s", $name);
$stmt->execute();
if($stmt->num_rows >= 1) { //if there is a registered member
$stmt->close();
$conn->close();
return true;
}
else {
$stmt->close();
$conn->close();
return false;
}
}
}
?>
Now I also tried to print num_rows but it just returns 0 as if there are no results inside the DB.
The usage is quite simple
if($player->isRegistered("Test") == true) {
echo "Hello";
}
else {
echo "Non-existing user";
}
SQL screenshot
http://imgur.com/a/TXqiJ
Also this is the sql class pastebin.com/Evg13CUc
The problem was resolved.
I used $stmt->store_result(); which somehow worked out and it gave me the good results.