Inserting data in diferent tables - php

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 */
?>

Related

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

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

Changing A Value in table saving issue

This code should check if the row col intersection of LikedOne and the row where username is jim equals text "empty".
$stmt1 = $conn->prepare("SELECT likedOne FROM UserData WHERE username = ?");
$stmt1->bind_param('s',$username);
//$username = $_POST["username"];
$username ="jim";
$stmt1->execute();
$stmt1->store_result();
$res = $stmt1->fetch();
if ( $res == "empty"){
echo "debug 3";
$sql = $conn->prepare("UPDATE UserData SET likedOne=? WHERE username=?");
$sql->bind_param('ss',$TUsername,$Username);
// $TUsername = $_POST["TUsername"];
// $Username = $_POST["username"];
$TUsername = "test";
$Username = "jim";
$sql->execute();
}
The first time it does change it to test but then it still prints debug 3 meaning it it still registering the $res as "empty" even though it should be "test".
Edit that is not working!
$stmt1 = $conn->prepare("SELECT likedOne FROM UserData WHERE username = ?");
$stmt1->bind_param('s',$username);
//$username = $_POST["username"];
$username ="jim";
$stmt1->execute();
$stmt1->bind_result($res);
$found_row = $stmt1->store_result();
if ( $found_row && $res == "empty"){
echo "debug 3";
$sql = $conn->prepare("UPDATE UserData SET likedOne=? WHERE username=?");
$sql->bind_param('ss',$TUsername,$Username);
// $TUsername = $_POST["TUsername"];
// $Username = $_POST["username"];
$TUsername = "test";
$Username = "jim";
$sql->execute();
}
$stmt1->fetch() doesn't return the contents of the likedOne column. It returns TRUE if a row was returned, NULL if there are no more rows in the result set, or FALSE if an error occurred.
To retrieve the data returned by a prepared statement, you need to use $stmt1->bind_result().
$stmt1 = $conn->prepare("SELECT likedOne FROM UserData WHERE username = ?");
$stmt1->bind_param('s',$username);
//$username = $_POST["username"];
$username ="jim";
$stmt1->execute();
$stmt1->bind_result($res);
$found_row = $stmt1->store_result();
if ($found_row && $res == "empty") {
...
}
I'm not sure why your code that does this isn't working, but it's not necessary to do two queries, you can do it in one.
$sql = $conn->prepare("UPDATE UserData SET likedOne=? WHERE username=? AND likedOne = 'empty'");
$sql->bind_param('ss',$TUsername,$Username);
//$TUsername = $_POST["TUsername"];
//$Username = $_POST["username"];
$TUsername = "test";
$Username = "jim";
$sql->execute();

PHP MySQL - Check if a specifc column was updated

I am trying to see the best approach for this scenario - i want to send an email alert whenever a user updates a specific column. The column name is rep. If the rep column isnt updated, do not send an email.
Here's my attempt:
<?php
include_once("connection.php");
if(isset($_POST['update'])) {
$id = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$record_update = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$comment = mysqli_real_escape_string($mysqli, $_POST['comment']);
$status = mysqli_real_escape_string($mysqli, $_POST['status']);
$rt = mysqli_real_escape_string($mysqli, $_POST['rt']);
$reason = mysqli_real_escape_string($mysqli, $_POST['reason']);
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$rep = mysqli_real_escape_string($mysqli, $_POST['rep']);
if(empty($record_update) ) {
if(empty($record_update)) {
echo "<script type='text/javascript'>alert('Date/Time field is blank.');window.location.href='dashboard.php';</script>";
}
} else {
$result = mysqli_query($mysqli, "UPDATE employee SET record_update='$record_update', comment='$comment', status='$status', rt='$rt', reason='$reason', username='$username', rep='$rep' WHERE id='$id'");
if($rep->(success() == true)) {
//do email
}
}
?>
so would it look like this?
<?php
include_once("connection.php");
if(isset($_POST['update'])) {
$id = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$record_update = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$comment = mysqli_real_escape_string($mysqli, $_POST['comment']);
$status = mysqli_real_escape_string($mysqli, $_POST['status']);
$rt = mysqli_real_escape_string($mysqli, $_POST['rt']);
$reason = mysqli_real_escape_string($mysqli, $_POST['reason']);
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$rep = mysqli_real_escape_string($mysqli, $_POST['rep']);
if(empty($record_update) ) {
if(empty($record_update)) {
echo "<script type='text/javascript'>alert('Date/Time field is blank.');window.location.href='dashboard.php';</script>";
}
} else {
$query = mysqli_query($mysqli, "SELECT rep FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['rep'] != $_POST['rep']) {
//do nothing
} else {
//do email
}
$result = mysqli_query($mysqli, "UPDATE employee SET record_update='$record_update', comment='$comment', status='$status', rt='$rt', reason='$reason', username='$username', rep='$rep' WHERE id='$id'");
}
?>
Select the current value, and compare it to the inserted value, if it's different it needs to be updated?
$query = mysqli_query($mysqli, "SELECT rep FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['rep'] != $_POST['rep'])
$record_update = true;
This might not be the best answer but I like to suggest that you capture the date and time of the first insert and then the update record them in a table columns and the compare the time or both when an update happens to the same data row.
$query = mysqli_query($mysqli, "SELECT time, date FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['time'] > $_POST['time'] || $row['date'] > $_POST['date'])
$record_update = true;

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

Updating password mysqli in PHP if a new one is entered

I'm a little new to PHP and mysqli and don't think I'm going around this the right way; maybe I need to check if it's the same, and if not update the password? I'm not sure how to do this though.
At the moment on the user edit form I'm not passing the current password value, but I can pass it and it will pass as md5 format.
PHP
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
$password = md5($_POST['password']); // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}
You did one mistake in your code.do not use MD5 before checking blank password . MD5 also encrypt blank value so $password == '' condition always wrong.
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
/// do not use md5 here so condition get false always
$password = $_POST['password']; // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
$password = md5($password);
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}

Categories