Need help to insert many rows in my SaaS project using PDO - php

I'm trying to develop a SaaS project. I have to, when the new company register, it automatically registers all permission params and permission groups it's going to have. The code is working including a company, a user in that company within the permission group Admin and he has clients view permission.
Now I need to add the other permissions the same way, they have to be created and added to the admin group just created. I'm trying this, but it only adds the first param (clients_view) and not the second param (clients_edit)
<?php
require_once 'config.php';
$name = isset($_POST['name']) ? $_POST['name'] : null;
$cnpj = isset($_POST['cnpj']) ? $_POST['cnpj'] : null;
$username = isset($_POST['username']) ? $_POST['username'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if (empty($name) || empty($cnpj) || empty($username) || empty($email) || empty($password) ){
echo "Please fill all fields";
exit;
}
//Creates the new company
$PDO = db_connect();
$sql = "INSERT INTO companies (name, cnpj) VALUES(:name, :cnpj)";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':cnpj', $cnpj);
$stmt->execute();
//creates permission param clients_view
$id_company = $PDO->lastInsertId();
$name = 'clients_view';
$sql2 = "INSERT INTO permission_params (id_company, name) VALUES (:id_company, :name)";
$stmt2 = $PDO->prepare($sql2);
$stmt2->bindParam(':id_company', $id_company);
$stmt2->bindParam(':name', $name);
$stmt2->execute();
//creates permission group Admin with param clients_view
$params = $PDO->lastInsertId();
$name = 'Admin';
$sql3 = "INSERT INTO permission_groups (id_company, name, params) VALUES (:id_company,:name, :params)";
$stmt3 = $PDO->prepare($sql3);
$stmt3->bindParam(':id_company', $id_company);
$stmt3->bindParam(':name', $name);
$stmt3->bindParam(':params', $params);
$stmt3->execute();
//create new user and adds to Admin group
$id_group = $PDO->lastInsertId();
$sql4 = "INSERT INTO users (username, email, password, id_group, id_company) "
. "VALUES (:username, :email, :password, :id_group, :id_company)";
$stmt4 = $PDO->prepare($sql4);
$stmt4->bindParam(':username', $username);
$stmt4->bindParam(':email', $email);
$stmt4->bindParam(':password',md5($password));
$stmt4->bindParam(':id_group', $id_group);
$stmt4->bindParam(':id_company', $id_company);
$stmt4->execute();
//creates permission clients_edit
// NOT WORKING
$name = 'clients_edit';
$sql5 = "INSERT INTO permission_params (name) VALUES (:name) WHERE id_company=:id_company";
$stmt5 = $PDO->prepare($sql5);
$stmt5->bindParam(':name', $name);
$stmt5->bindParam(':id_company', $id_company);
$stmt5->execute();
//Insert permission clients_view in group Admin
//NOT WORKING
$params = $PDO->lastInsertId();
$sql6 = "INSERT INTO permission_groups ( params) VALUES ( :params) WHERE name=:name AND id_company=:id_company";
$stmt6 = $PDO->prepare($sql6);
$stmt6->bindParam(':params', $params);
$stmt6->bindParam(':name', $name);
$stmt6->bindParam(':id_company', $id_company);
$stmt6->execute();
header('Location: index.php');

INSERT INTO permission_params (name) VALUES (:name) WHERE id_company=:id_company
That's wrong. You can't INSERT that again in that ID. You can INSERT new with new ID, or you can UPDATE that ID with new name OR you can create new table there insert ID from this table and on that way connect some other table with this table. If you know what I mean, maybe not the best explanation :D

Related

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

delete a record from the specified table in MySQL with PHP

I'm working on a registration form with MySQL and PHP, I have 2 table in MySQL: users and a_codes.
before I defined and insert some username into the a_codes table.
when a user enters a username in the registration form.it's checked with records in the a_codes table, if exist then registration done.
my problem is that I want after the user successfully registered, the mentioned username in the a_codes table must be deleted.
everything in my code below worked fine. the only question is how to delete the used username in the a_codes table?
. I'm new in PHP and thanks for any help.
<?php
require_once 'DbConnect.php';
//an array to display response
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'signup':
//checking the parameters required are available or not
if(isTheseParametersAvailable(array('username','email','password','gender'))){
//getting the values
$username = $_POST['username'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$gender = $_POST['gender'];
//checking if the user is already exist in a_codes table with this username
$stmt = $conn->prepare("SELECT id FROM a_codes WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
//if the user already exist in the database
if($stmt->num_rows > 0){
//if user is already exist creating an insert query
$stmt = $conn->prepare("INSERT INTO users (username, email, password, gender) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $password, $gender);
//if the user is successfully added to the database
if($stmt->execute()){
//fetching the user back
$stmt = $conn->prepare("SELECT id, id, username, email, gender FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($userid, $id, $username, $email, $gender);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email,
'gender'=>$gender
);
$stmt->close();
//adding the user data in response
$response['error'] = false;
$response['message'] = 'done';
$response['user'] = $user;
}
} else {
$response['error'] = true;
$response['message'] = 'already registered';
$stmt->close();
}
}else{
$response['error'] = true;
$response['message'] = 'error eccoured';
}
break;
The correct syntax for mysql delete is;-
DELETE FROM table_name WHERE column = value;
in your case it will be
DELETE FROM `a_codes` WHERE `username` = "insert the username here"
or
$stmt = $conn->prepare("DELETE FROM a_codes WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

How do I insert the primary key to another table as foreign key?

I have two tables
tbl_cars and tbl_user
Where tbl_user has userID as Primary key
I declared it as a Foreign key on my tbl_cars
Whenever a user logs in it can't post an item to the tbl_cars I get this error
Cannot add or update a child row: a foreign key constraint fails
(u850332371_car.tbl_cars, CONSTRAINT tbl_cars_ibfk_1 FOREIGN KEY
(userID) REFERENCES tbl_user (userID))
This is my code for inserting.
Insert.php
<?PHP
$conn = new mysqli('******', '******', '******', '******');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
error_reporting(E_ALL);
ini_set('display_errors',1);// at top of page
if(isset($_POST['txtCarModel']) && isset($_POST['txtCarType']) &&
isset($_POST['txtCapacity']) && isset($_POST['image']) &&
isset($_POST['txtFuelType']) && isset($_POST['txtPlateNumber'])){
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHis');
$upload_folder = "upload";
$path = "$upload_folder/$id.jpeg";
$image = $_POST['image'];
$fullpath = "http://carkila.esy.es/$upload_folder/$id.jpeg";
$Car_Model = $_POST['txtCarModel'];
$Car_Type = $_POST['txtCarType'];
$Capacity = $_POST['txtCapacity'];
$Fuel_Type = $_POST['txtFuelType'];
$PlateNumber = $_POST['txtPlateNumber'];
$Image = $_POST['image'];
$stmt = $conn->prepare("INSERT INTO tbl_cars (Car_Model, Car_Type, Capacity, fuelType, carPlatenuNumber, Image) VALUES (?, ?, ?,?,?,?)");
$query = "INSERT INTO tbl_cars(Car_Model, Car_Type, Capacity,fuelType, carPlatenuNumber, Image)
VALUES ('$Car_Model', '$Car_Type', $Capacity, '$Fuel_Type', '$PlateNumber', '$fullpath')";
$stmt->bind_param("ssssss", $Car_Model, $Car_Type, $Capacity,$Fuel_Type,$PlateNumber, $fullpath);
$result = $stmt->execute();
if($result === false ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}else{
echo "New records created successfully";
}
$stmt->close();
$conn->close();
}
?>
UPDATE
This is my login with sessions. I want the userID to be in the insertion of data to the database.
login.php
<?php
require 'database-config.php';
session_start();
$username = "";
$password = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
$q = 'SELECT * FROM tbl_user WHERE username=:username AND password=:password';
$query = $dbh->prepare($q);
$query->execute(array(':username' => $username, ':password' => $password));
if($query->rowCount() == 0){
header('Location: index.php?err=1');
}else{
$row = $query->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['userID'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['roles'];
echo $_SESSION['sess_userrole'];
session_write_close();
if( $_SESSION['sess_userrole'] == "renter"){
echo "owner";
}else if ($_SESSION['sess_userrole'] == "owner"){
echo"renter";
}
}
?>
Thank you guys. :)
whenever a user logs in it can't post an item...
Since you know which user is trying to add a record to tbl_cars, include userID in your insert.
$userID = ... //<- put the user id in this variable
$sql = 'INSERT INTO tbl_cars ('.
'userID,Car_Model,Car_Type,Capacity,fuelType,carPlatenuNumber,Image'.
') VALUES (?, ?, ?, ?, ?, ?, ?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $userID $Car_Model, $Car_Type, $Capacity,
$Fuel_Type,$PlateNumber, $fullpath);
$result = $stmt->execute();
I believe your problem is that userID is a required field, but the DB cannot insert a default value for you when you don't provide one because the value must be bound to a primary key in tbl_user

Check if the email exists using pdo

This is the section I use to add users.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: ./index.php");
}
require 'conn.php';
$message = '';
if(!empty($_POST['name']) &&!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
I personally do it by using a query and an if statement
$query = $conn->prepare("SELECT * FROM users WHERE email = :email");
$query->bindParam(':email', $_POST['email']);
if ($query->rowcount() = 0)
{
// insert account into database
}
else {
// display error message
}
To check if the email exists or not, you have to write a query whether that email is stored in the database. If the query result is not empty, you can show a message that the email exists. If the query result is empty, you can make him a new user.
For that you have to write this query
$sql="select name from user where email='$email'";
$stmt = $conn->prepare($sql);
if ($stmt->rowcount() = 0)
{
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
}
else {
$msg="Email already exists";
}

INSERT INTO SQL php Function does not work

I have managed to write a php script that checks if a username already exists in the database and only adds a new user if it does not already exist.
This is my php script:
<?php
require "init.php";
if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
$username = $_POST['username'];
$forename = $_POST['forename'];
$username = $_POST['surname'];
$password = $_POST['password'];
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon -> prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($username);
if($result->fetch()){
echo "Can't add new user as it already exists!";
}
else{
$stmt_two = "INSERT INTO users (username, forename, surname, password)
VALUES(?, ?, ?, ?)";
$result_two = $dbcon -> prepare($stmt_two);
$result_two->bind_param('ssss', $username, $forename, $surname, $password);
$result_two->execute();
$result_two->close();
echo json_encode("Success");
}
}
?>
I believe the records are not being inserted or being inserted intermittently due to the fact that I have more than one prepared statement. If I just do the INSERT INTO statement on its' own with the SELECT FROM statement - the records are added almost instantly.
Why is this and what is wrong with my code?
Thanks
Just as I have said in the comments, don't over complicate and just check the number of rows found. No need to fetch anything. You're just checking if that user exists anyway.
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();
if($result->num_rows() > 0) { // if it exists
} else {
// make your insertions
}
And another note:
isset can take multiple arguments:
if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
// and so on
}
Edit: Another flavor (using COUNT() of MySQL):
$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();
if($count > 0) { // exists
} else {
// do something else
}

Categories