Problems entering information in MySQL database - php

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

Related

Query doesn't insert into table

I using a register form and i would like to see if i have missing columns/tables. I'm using var_dump $stmt; and echo $e->getMessage();
Every time I get successfully message but the code doesn't insert anything into the database .
If I'm using echo $e->getMessage(); I get this:
object(PDOStatement)#11 (1) { ["queryString"]=> string(153) "INSERT INTO bg_user(user_id, passwd, email, account_status) VALUES(:login, :password, :email, :status)" }
Notice: Undefined variable: e in include\classes\user.php on line 89
Fatal error: Uncaught Error: Call to a member function getMessage() on null in include\classes\user.php:89 Stack trace:
#0 include\functions\register.php(57): USER->register('test123', 'a3876fafbc8b9b9...', 'test#tex.com', NULL)
#1 pages\register.php(11): include('D:\Working Stat...')
#2 index.php(199): include('D:\Working Stat...')
#3 {main} thrown in include\classes\user.php on line 89
This is my code:
public function register($username,$password,$email,$ref)
{
global $safebox_size;
try
{
$password = md5($password);
$social_id = rand(1000000, 9999999);
$status = "OK";
$stmt = $this->account->prepare("INSERT INTO bg_user(user_id, passwd, email, account_status)
VALUES(:login, :password, :email, :status)");
$stmt->bindparam(":login", $username);
$stmt->bindparam(":password", $password);
$stmt->bindparam(":email", $email);
$stmt->bindparam(":status", $status);
$stmt->execute();
$lastId = $this->account->lastInsertId();
$safebox_password = "000000";
$stmt = $this->player->prepare("INSERT INTO safebox(account_id, size, password)
VALUES(:account_id, :size, :password)");
$stmt->bindparam(":account_id", $lastId);
$stmt->bindparam(":size", $safebox_size);
$stmt->bindparam(":password", $safebox_password);
$stmt->execute();
if($ref && count(getAccountInfo($ref)))
addReferral($lastId, $ref);
return $stmt;
}
catch(PDOException $e)
{
//echo $e->getMessage();
print 'ERROR';
}
}
My question is: what command do I have to use for var_dump, echo, print etc. to report errors (missing columns or tables)?

Calling a function of a class does not work 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);
}

PDO returns unknown error message on execute

I´m developing a website using php and I tried to implement pdo but it keeps returning
PDO::errorInfo():Array([0] => 00000 [1] => [2] => )
It´s very important that I can fix these error since this is an important project for me and I´ve tried everything I could.
the connection works fine since I
Any ideas?
Here is the connection (in case you need it):
<?php
$redirect ="503.php";
$config = parse_ini_file('config.ini');
$basehost = $config['host'];
$basecon = $config['table'];
$seccon = $config['sectable'];
$basechar = $config['char'];
$smhost = $config['SMTPhost'];
$smauth = $config['SMTPAuth'];
$smuser = $config['SMTPUser'];
$smpass = $config['SMTPPass'];
$smsec = $config['SMTPSecure'];
$cartab = $config['cardtable'];
$con = "mysql:host=$basehost;dbname=$basecon;charset=$basechar";
$options = [PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,];
try {
$pdo = new PDO($con,$config['username'],$config['password'], $options);
} catch (Exception $e) {
exit(header("location:$redirect"));
}
?>
Here is the problem I can´t handle:
if($mail->send()) {
$stmt = $pdo->prepare("INSERT INTO $basecon.$seccon (C_Nome,C_email,C_User,C_Pass,Card_Number,N_fiscal,D_Nasc,C_Morada,N_tel,N_tel_emer,N_cid,N_saude,Tipo_Sangue,C_Hist,Reg_Code) VALUES (:name, :email,:user,:pass,:cardnum,:fisnum,:birth,:adressnum,:telf,:emertelf,:citcard,:healthcard,:bloodstring,:histstring,:value)");
$stmt->bindParam(array(':name', $_POST['name']), PDO::PARAM_STR);
$stmt->bindParam(array(':email', $_POST['email']), PDO::PARAM_STR);
$stmt->bindParam(array(':user', $_POST['username']), PDO::PARAM_STR);
$stmt->bindParam(array(':pass', md5($_POST['password'])), PDO::PARAM_STR);
$stmt->bindParam(array(':cardnum', $_POST['cardnumber']), PDO::PARAM_STR);
$stmt->bindParam(array(':fisnum', $_POST['fiscalnum']), PDO::PARAM_STR);
$stmt->bindParam(array(':birth', $_POST['birthdate']), PDO::PARAM_STR);
$stmt->bindParam(array(':adressnum', $_POST['address']), PDO::PARAM_STR);
$stmt->bindParam(array(':telf', $_POST['telnum']), PDO::PARAM_STR);
$stmt->bindParam(array(':emertelf', $_POST['emertelnum']), PDO::PARAM_STR);
$stmt->bindParam(array(':citcard', $_POST['citnumber']));
$stmt->bindParam(array(':healthcard', $_POST['healthnumber']), PDO::PARAM_STR);
$stmt->bindParam(array(':bloodstring', $_POST['bloodtype']), PDO::PARAM_STR);
$stmt->bindParam(array(':histstring','Conta criada a'), PDO::PARAM_STR);
$stmt->bindParam(array(':value', $regcode), PDO::PARAM_STR);
if($stmt->execute()) {
$successmsg = "Your registration was successful! <a href='login.php'>Clique aqui para efetuar login</a><br>";
} else {
$errormsg = "We couldn´t send you the confirmation E-mail, please check if you provided us with the correct E-mail, if so, please try again later.";
}
} else {
echo "\nPDO::errorInfo():\n";
print_r($pdo->errorInfo());
$errormsg = '<div class="alert alert-danger" role="alert">Something went wrong, please try again later." </div>' ;
}
And the E-mail works so that has nothing to do with the problem.
And thank you :)
Your error conditions are in the wrong order. The error is in sending mail, but you display a database error which is, as expected, empty. Proper and consistent indenting will help spot these sorts of problems.
It's also worth noting that you don't need to bind parameters with PDO, and you can use ? placeholders.
One last edit, you enable exceptions during database initialization, but don't use it later in the code. If there's a problem in your database query it won't return false but will throw an exception instead.
if($mail->send()) {
try {
$stmt = $pdo->prepare("INSERT INTO $basecon.$seccon (C_Nome,C_email,C_User,C_Pass,Card_Number,N_fiscal,D_Nasc,C_Morada,N_tel,N_tel_emer,N_cid,N_saude,Tipo_Sangue,C_Hist,Reg_Code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
$_POST['name'],
$_POST['email'],
$_POST['username'],
password_hash($_POST['password']),
$_POST['cardnumber'],
$_POST['fiscalnum'],
$_POST['birthdate'],
$_POST['address'],
$_POST['telnum'],
$_POST['emertelnum'],
$_POST['citnumber'],
$_POST['healthnumber'],
$_POST['bloodtype'],
'Conta criada a',
$regcode,
]) {
$successmsg = "Your registration was successful! <a href='login.php'>Clique aqui para efetuar login</a><br>";
} catch (\Exception $e) {
// of course you should never catch errors just to display them, this is just a demo
echo $e->getMessage();
print_r($pdo->errorInfo());
$errormsg = '<div class="alert alert-danger" role="alert">Something went wrong, please try again later." </div>';
}
} else {
$errormsg = "We couldn´t send you the confirmation E-mail, please check if you provided us with the correct E-mail, if so, please try again later.";
}

trying to test API using postman

i am trying to test an api using postman , each time i try to signup i keep getting "unexpected e".
Don't really know what is going on
here is my code:
$app->post('/signup', function() {
$app = \Slim\Slim::getInstance();
$name = $app->request()->post('name');
$email = $app->request()->post('email');
$pass = $app->request()->post('pass');
$app->response->setStatus(200);
$app->response()->headers->set('Content-Type', 'application/json');
try
{
$db = getDB();
$sth = $db->prepare("select count(*) as count from user WHERE email=:email");
$sth->bindParam(':email', $email, PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetch();
if($row['count']>0){
$output = array(
'status'=>"0",
'operation'=>"student already registered"
);
echo json_encode($output);
$db = null;
return;
}
else{
// where i try to insert values into my database.
$sth = $db->prepare("INSERT INTO user (name, email,password)
VALUES(:name,:email,:pass)");
$sth->bindParam(':name', $name, PDO::PARAM_INT);
$sth->bindParam(':email', $email, PDO::PARAM_INT);
$sth->bindParam(':pass', $pass, PDO::PARAM_INT);
$sth->execute();
$output = array(
'status'=>"1",
'operation'=>"success"
);
echo json_encode($output);
$db = null;
return;
}
}
catch(Exception $ex){
echo $ex;
}
});
"unexpected e" happens because Postman was expecting the output to be a JSON response.
When you get the response, click the 'Raw' or 'Preview' tab. Or choose one of the other formats from the drop-down menu. You'll see the rest of the response.

An "insert into" mySQL query through PHP appears to work, but nothing is added

EDIT: I realized my problem was that I was trying to insert $user_id, which has a string with numbers" into column user_id, which is type int. I converted the string into an integer. I still didn't quite figure out errors though, but that's because of time constraints. I'll get back to it some other time.
I'm trying to build a website on top of the advanced version of the php login system provided at http://www.php-login.net. In the Registration class of the script, there's a function that adds a new user to the database, and that code works totally fine:
$query_new_user_insert = $this->db_connection->prepare('INSERT INTO users (user_name, user_password_hash, user_email, user_activation_hash, user_registration_ip, user_registration_datetime) VALUES(:user_name, :user_password_hash, :user_email, :user_activation_hash, :user_registration_ip, now())');
$query_new_user_insert->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_new_user_insert->bindValue(':user_password_hash', $user_password_hash, PDO::PARAM_STR);
$query_new_user_insert->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_new_user_insert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
$query_new_user_insert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$query_new_user_insert->execute();
// id of new user
$user_id = $this->db_connection->lastInsertId();
if ($query_new_user_insert) {
// send a verification email
if ($this->sendVerificationEmail($user_id, $user_email, $user_activation_hash)) {
// when mail has been send successfully
$this->messages[] = $this->lang['Verification mail sent'];
$this->registration_successful = true;
} else {
// delete this users account immediately, as we could not send a verification email
$query_delete_user = $this->db_connection->prepare('DELETE FROM users WHERE user_id=:user_id');
$query_delete_user->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$query_delete_user->execute();
$this->errors[] = $this->lang['Verification mail error'];
}
} else {
$this->errors[] = $this->lang['Registration failed'];
}
I tried copying that code for another part of my site using the following code:
public function addNewTag($postContent) {
if ($this->databaseConnection()) {
$query_add_tag = $this->db_connection->prepare('INSERT INTO tags (tag_name, tag_short_name, tag_id, color, user_id, creation_time)
VALUES(:tag_name, :tag_short_name, :tag_id, :color, :user_id, :creation_time)');
$query_add_tag->bindValue(':tag_name', $postContent['tag_name'], PDO::PARAM_STR);
$query_add_tag->bindValue(':tag_short_name', $postContent['tag_short_name'], PDO::PARAM_STR);
$query_add_tag->bindValue(':tag_id', rand(100000000000, 999999999999), PDO::PARAM_STR);
$query_add_tag->bindValue(':color', $postContent['color'], PDO::PARAM_STR);
$query_add_tag->bindValue(':user_id', $user_id, PDO::PARAM_STR);
$query_add_tag->bindValue(':creation_time', time(), PDO::PARAM_STR);
$query_add_tag->execute();
if ($query_add_tag) {
return true;
} else {
return false;
}
} else {
return false;
}
}
The function is called with $_POST as the variable for $postContent with the code
$content->addNewTag($_POST);
When I do so, the function returns true ("1"), but when I check my database content, nothing is added. What could be the issue here? I'm not that great with mySQL, so maybe it's an obvious error somewhere else in my script.
Are you running in autocommit=0? If so, please set autocommit=1 or add commit at the end of your function. Should be something like:
$query_add_tag->commit();

Categories