foreign key does not update on cascade - php

I am using phpmyadmin 4.7.3 version. I made 2 tables with innoDB storage engine in a same database and i want to update foreign key automatically by using cascade but it does not work at all. In my dineOwnerUser table i have id field which is foreign key in webpromo table with the name of ownerid. Here are all step which i did to make it foreign key.
went to webpromo table
clicked on relation view button
after that i setup all option which is visible in image
So far i have explained which i have done the problem is that my webpromo table is totally empty even though foreign key is also not updating automatically. If i am wrong here kindly please guide me also I am posting my code just in case i am doing some thing wrong in coding here is my php code
<?php
session_start();
if(isset($_POST['recaptcha'])){
$secret = "************";
$response = $_POST['recaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$content = json_decode($url, TRUE);
if($content['success'] ==1){
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strtolower($data);
return $data;
}
$discount = test_input($_POST["discount"]);
$discountitem = test_input($_POST["discountitem"]);
$website = test_input($_POST["website"]);
$expirydate = test_input($_POST["expirydate"]);
$desc = test_input($_POST["desc"]);
$filename;
if(isset($_FILES['logouploader']['name'])){
$filename = basename($_FILES['logouploader']['name']);
$filename = test_input($filename);
}
$dir = "img/uploads/";
$ext = strtolower(pathinfo($_FILES['logouploader']['name'], PATHINFO_EXTENSION));
$allowed = array('jpeg','png' ,'jpg');
if(!in_array($ext,$allowed) ) {
echo "wrongext";
$uploadOk = 0;
exit;
}
if ($_FILES["logouploader"]["size"] > 600000) {
echo "large";
$uploadOk = 0;
exit;
}
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry";
exit;
}
if ($uploadOk == 1) {
move_uploaded_file($_FILES["logouploader"]["tmp_name"], $dir.$filename);
$servername = "localhost";
$username = "*****";
$password = "*****";
try {
$conn = new PDO("mysql:host=$servername;dbname=*********", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO webpromo (discount, dealitem, website, expirydate, description, logouploader) VALUES (?, ?, ?, ?, ?, ?)";
$statement = $conn->prepare($query);
$statement->execute(
array(
$discount,
$discountitem,
$website,
$expirydate,
$desc,
$filename
) );
$conn = null;
exit;
echo "done";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
}
if($content['success'] !=1){
echo "notok";
$conn = null;
exit;
}
$conn = null;
exit;
}
?>
Note: i am getting image in my folder that's mean upto
move_uploaded_file($_FILES["logouploader"]["tmp_name"], $dir.$filename); my code is working fine
but after that when i try to populate my webpromo table with the form input values as well as uploaded image name it does not populate at all.
Thanks

You have got the wrong idea my friend it does not mean your data will be automatically inserted if you are using cascade.
What is used for actually is if the primary key value is updated then it updates the foreign key value in all respective tables.
You have to write a seperate insert query.

Related

How to solve duplicate entry, and instead, have one entry inserted into mysql table?

<?php
//open connection to mysql db
$connect = mysqli_connect("localhost","root"," ","tutorial") or die("Error " . mysqli_error($connect));
$offence_place = $_POST["offence_place"];
$vehicle_no = $_POST["vehicle_no"];
$offence_type = $_POST["offence_type"];
$offence_lotnumber = $_POST["offence_lotnumber"];
$offence_charges = $_POST["offence_charges"];
$query = " Insert into eSummon(offence_place, vehicle_no, offence_type, offence_lotnumber, offence_charges, image_name, image_path)
values ('$offence_place','$vehicle_no','$offence_type','$offence_lotnumber','$offence_charges','$image_name','$path');";
mysqli_query($connect,$query) or die (mysqli_error($connect));
// IMAGE
header('Content-type : bitmap; charset=utf-8');
// Image Connection to Database
if (isset($_POST["encoded_string"])){
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
// Save image on the server
$path = 'images/'.$image_name;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
// Save the path to the Database
if($is_written > 0) {
// Open connection to mysql Database
$connect = mysqli_connect("localhost","root"," ","tutorial") or die("Error " . mysqli_error($connect));
$query = " Insert into eSummon(offence_place, vehicle_no, offence_type, offence_lotnumber, offence_charges, image_name, image_path)
values ('$offence_place','$vehicle_no','$offence_type','$offence_lotnumber','$offence_charges','$image_name','$path');";
$result = mysqli_query($connect, $query) or die("Error in Selecting " . mysqli_error($connect));
if($result){
echo "Success";
}else{
echo "Failed";
}
mysqli_close($connect);
}
}
?>
Once I run the php codes above, I will get 2 entries of different IDs in mysql table shown below. The first entry (ID:71) does not contain the $image_name and $image_path, but the second entry (ID:72) contains all the data in the first entry with the $image_name and $image_path. Thus, I get two entries in the table when I only want to see one entry with all the data inserted. Is there a way to solve this issue that I am having? Thank you.
mysql table entries
Then you should insert one only instead of 2.
This is the reason, why it will have a duplicate entry
mysqli_query($connect,$query) --> you use this twice
Remove some of your top code, and turn your code to this :
<?php
if (isset($_POST["encoded_string"])){
$offence_place = $_POST["offence_place"];
$vehicle_no = $_POST["vehicle_no"];
$offence_type = $_POST["offence_type"];
$offence_lotnumber = $_POST["offence_lotnumber"];
$offence_charges = $_POST["offence_charges"];
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
// Save image on the server
$path = 'images/'.$image_name;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
// Save the path to the Database
if($is_written > 0) {
// Open connection to mysql Database
$connect = mysqli_connect("localhost","root"," ","tutorial") or die("Error " . mysqli_error($connect));
$query = " Insert into eSummon(offence_place, vehicle_no, offence_type, offence_lotnumber, offence_charges, image_name, image_path)
values ('$offence_place','$vehicle_no','$offence_type','$offence_lotnumber','$offence_charges','$image_name','$path');";
$result = mysqli_query($connect, $query) or die("Error in Selecting " . mysqli_error($connect));
if($result){
echo "Success";
}else{
echo "Failed";
}
mysqli_close($connect);
}
}
?>
Typically you would use the insert into table on duplicate key update syntax - assuming there is a primary key of some sort
$sql="insert into `eSummon`(`offence_place`, `vehicle_no`, `offence_type`, `offence_lotnumber`, `offence_charges`, `image_name`, `image_path`)
values ( '$offence_place', '$vehicle_no', '$offence_type', '$offence_lotnumber', '$offence_charges', '$image_name', '$path')
on duplicate key update
`offence_place`='$offence_place',
`vehicle_no`='$vehicle_no',
`offence_type`='$offence_type',
`offence_lotnumber`='$offence_lotnumber',
`offence_charges`='$offence_charges',
`image_name`='$image_name',
`image_path`='$path';";
<?php
/* Create db connection object */
$connect = new mysqli( 'localhost', 'root', ' ', 'tutorial' ) or die('Error: unable to connect to db ');
/* Get the variables assigned */
$offence_place = $_POST['offence_place'];
$vehicle_no = $_POST['vehicle_no'];
$offence_type = $_POST['offence_type'];
$offence_lotnumber = $_POST['offence_lotnumber'];
$offence_charges = $_POST['offence_charges'];
/* Ensure there is a default value for these */
$path = $image_name='';
/* Create the sql statement */
$sql="insert into `eSummon`( `offence_place`, `vehicle_no`, `offence_type`, `offence_lotnumber`, `offence_charges`, `image_name`, `image_path` )
values ( ?, ?, ?, ?, ?, ?, ? )
on duplicate key update
`offence_place`=?,
`vehicle_no`=?,
`offence_type`=?,
`offence_lotnumber`=?,
`offence_charges`=?,
`image_name`=?,
`image_path`=?;";
/* Use aprepared statement */
$stmt=$connect->prepare( $sql );
$stmt->bind_params( 'sssssss', $offence_place,$vehicle_no,$offence_type,$offence_lotnumber,$offence_charges,$image_name,$path );
$stmt->execute();
/* Why this header? If you echo text further it will break the image! */
header('Content-type: bitmap; charset=utf-8');
if( isset( $_POST['encoded_string'] ) ){
$encoded_string = $_POST['encoded_string'];
$image_name = $_POST['image_name'];
$decoded_string = base64_decode( $encoded_string );
$path = 'images/'.$image_name;
$file = fopen( $path, 'wb' );
$is_written = fwrite( $file, $decoded_string );
fclose( $file );
if( $is_written > 0 ) {
/* New values have been assigned to image_name and path, execute statement again */
$res=$stmt->execute();
echo $res ? 'Success' : 'Failed';/* this would break the image */
}
}
?>

send binary files from php to mysql using mysqli

i want to send data into two tables from a php script,the pic and idcard are two binary files that in mysql db and both of them have LONGBLOB type always the first insert query executed successfully(insert into user table) but the second query(insert into `applicant' table) have two situations:
1-if i make the pic and idcard field NULLABLE in db,other data except these two inserted successfully.
2-if i make the pic and idcard field NOT NULLABLE nothing insert into `applicant' table.
and both of two situation i cant save the binary data into my database,where is the problem?
and i also have no problem in $_FILES array and passing them,i can see the details of these fileds when i post it to the php script.
i think something is wrong with the send_long_data but i use it before exactly like now!
here is the script:
require_once('db_connection_config.php');
if (mysqli_connect_errno()) {
print_r("<div class='bs-example center-block'><div id='alertshow' class='bs-example center-block alert alert-danger'><a href='#' class='close' data-dismiss='alert'>×</a><strong>Connection Error:</strong>" . mysqli_connect_errno() . "</div></div>");
exit();
}
$today = date('Y:m:d');
$pass = randomPassword();
$stmt = $mysqli->prepare("INSERT INTO user (password,gender,firstname,lastname,email,phoneNum,mobileNum,Address,UserRoles_userRoleId) VALUES (?,?,?,?,?,?,?,?,3)");
$stmt->bind_param("sissssss", $pass, $_POST['gender'], $_POST['name'], $_POST['lastname'], $_POST['email'], $_POST['phonenum'], $_POST['mobilenum'], $_POST['address']);
$stmt->execute();
$mkey = mysqli_insert_id($mysqli);
$stmt->close();
if(isset($_FILES['pic']) && isset($_FILES['idcard'])){
$pic_file_path = $_FILES['pic']['tmp_name'];
if ( !file_exists($pic_file_path) ) {
throw new Exception('File not found.');
}
$pic_handle = fopen($pic_file_path, "rb");
if ( !$pic_handle ) {
throw new Exception('File open failed.');
}
$pic_content = null;
$idpic_file_path = $_FILES['idcard']['tmp_name'];
$idpic_handle = fopen($idpic_file_path, "rb");
$idpic_content = null;
$stmt = $mysqli->prepare("INSERT INTO applicant (userId,nationalCode,fatherName,birthPlace,nationality,religion,postalCode,picture,idpicture,registrationDate,militaryServiceStatus) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("isssiisbbss", $mkey, $_POST['nationalcode'], $_POST['fathername'], $_POST['birthcity'], $_POST['nationality'], $_POST['religion'], $_POST['postalcode'], $pic_content, $idpic_content, $today, $_POST['mss']);
while (!feof($pic_handle)) {
$stmt->send_long_data(1, fread($pic_handle, 8192));
}
fclose($pic_handle);
while (!feof($idpic_handle)) {
$stmt->send_long_data(1, fread($idpic_handle, 8192));
}
fclose($idpic_handle);
$stmt->execute();
$stmt->close();
}
}
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}

PHP : return last inserted Id on statement

So I want to get and return last inserted id from query.
I am successfully get the last inserted id but I have a little problem when try to return it to index.php file
This is my method code :
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
$stmt->execute();
$result = $this->conn->insert_id; <-- This is how I get the last inserted id
$stmt->close();
}
// Check for successful insertion
if ($result)
{
// User card successfully inserted
return USER_CARD_INSERTED_SUCCESSFULLY;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and this is my index.php file
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if ($UserCard == USER_CARD_INSERTED_SUCCESSFULLY)
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = SHOULD_BE_HERE;
echoRespnse(201, $response);
}
});
as you see, I want to put the last inserted id on $response["last_inserted_id"], but I do not know how to do it.
any ideas ?
thanks:)
I think you have your statements backwards
$inserted_id = $this->conn->insert_id;
$result = $stmt->execute();
In prepared statements, execute is what runs your SQL. So you can't get the ID of what hasn't been inserted yet.
$result = $stmt->execute();
$inserted_id = $this->conn->insert_id;
You're also not storing the data anywhere usable ($inserted_id is a local variable to your function). Consider making a class variable like $this->inserted_id and making a function that would return that value.
Try this in you method:
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
}
// Check for successful insertion
if ($stmt->execute())
{
$result = $this->conn->insert_id;
$stmt->close();
return $result;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and in you index.php:
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if (($UserCard != "USER_CARD_INSERT_FAILED") and ($UserCard != "USER_CARD_ALREADY_EXISTED"))
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = $UserCard;
echoRespnse(201, $response);
}
});
The way I read that, your // Check for successful insertion section will never run because the function is terminated with return $result; before the conditional. Therefore, USER_CARD_INSERTED_SUCCESSFULLY is never returned.
In my functions, I usually return an array, for example:
$result = array( "status" => $status, "id" => $id );
return $result;
and, in the main:
$result = my_function();
$status = $result['status'];
$id = $result['id'];
I hope this help you!
In your method code instead of using $inserted_id use a $_SESSION variable $_SESSION['inserted_id']. Now you will be able to use this in your index.php
$response["last_inserted_id"] = $_SESSION['inserted_id '];

Overwriting entries in a MYSQL database with new entries

I am trying to replace previous entries in MYSQL database each time new data is available, I have the following PHP code but it seems to add new entries each time. Please help, thanks.
I have tried using REPLACE but it still does not work, could anyone tell me what it is I am doing wrong?
<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$mysqli = new mysqli("localhost","dbuser","Pa55uu0Rd","iewdb");
if (mysqli_connect_errno())
{
echo json_encode(array('error' => 'Failed to connect to MySQL: ' . mysqli_connect_error() ));
return;
}
if(!$data)
{
echo json_encode(array('error' => 'Error input data'));
return;
}
$usernme = $data['usernme'];
$longitude = $data['longitude'];
$latitude = $data['latitude'];
$user = $mysqli->query("SELECT id FROM Users WHERE usernme = '$usernme' LIMIT 1");
$user_id = $user->fetch_object();
if(!$user_id)
{
$mysqli->query("INSERT INTO Users (usernme) VALUES ('$usernme');");
$user_id->id = $mysqli->insert_id;
}
if($longitude && $latitude)
{
$mysqli->query("REPLACE INTO Locations (User_id,Longitude, Latitude) VALUES ($user_id->id,$longitude,$latitude);");
}
$mysqli->close();
echo json_encode(array('user_id' => $user_id->id));
use update query something like this
UPDATE MyTable
SET User_id = 'USER_ID_VALUE', Longitude='LONGITUDE_VALUE', Latitude='LATITUDE_VALUE'
WHERE SomeOtherColumn LIKE '%PATTERN%'
Logic : Instead of replacing old entry you can delete that old entries and later add fresh entries into database will always good in case of performance..
So you will have to write one delete and insert query only...instead of 3 queries
Here is my solution to the problem and it works just fine. I decided to go with UPDATE as you can see below as I thought it was tidiest, thanks for the help.
<?php
header('Content-Type: application/json');
//get parameters
$data = json_decode(file_get_contents('php://input'), true);
// Create connection
$mysqli = new mysqli("localhost","dbuser","Pa55w0rd","ewdb");
// Check connection
if (mysqli_connect_errno())
{
echo json_encode(array('error' => 'Failed to connect to MySQL: ' . mysqli_connect_error() ));
return;
}
if(!$data)
{
echo json_encode(array('error' => 'Error input data'));
return;
}
$usernme = $data['usernme'];
$longitude = $data['longitude'];
$latitude = $data['latitude'];
$user = $mysqli->query("SELECT id FROM Users WHERE usernme = '$usernme' LIMIT 1");
$user_id = $user->fetch_object();
if(!$user_id)
{
$mysqli->query("INSERT INTO Users (usernme) VALUES ('$usernme');");
$user_id->id = $mysqli->insert_id;
$mysqli->query("INSERT INTO Locations (User_id) VALUES ($user_id->id);");
}
if($longitude && $latitude)
{
$mysqli->query("UPDATE Locations SET Longitude = $longitude, Latitude = $latitude WHERE User_id = $user_id->id;");
}
/* close connection */
$mysqli->close();
echo json_encode(array('user_id' => $user_id->id));

UPDATE SQL with Session

I am trying to insert image path into an existing databse. The code below works, but inserts a new row.
$address= htmlentities($_SESSION['address']);
$city= htmlentities($_SESSION['city']);
$zip_code= htmlentities($_SESSION['zip_code']);
$query =
"INSERT INTO property(name, size, type_picture, file_path, username) VALUES (?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
}else {
echo 'Success!<br/>';
echo '<img src="' . DISPLAY_PATH . $myfile . '"/>';
}
} else {
die("Error preparing Statement");
When I try the same as above but UPDATE, i get the "Error preparing Statement". I need to update empty cells (if this matters).
$query =
"UPDATE property(name, size, type_picture, file_path, username)
SET(?,?,?,?,?)
WHERE address = '$address' // with or without ''
city = '$city' ";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
} // etc. etc.
Thank you so much. Tried for a day, need some help.
Your update query is wrong, try this instead:
$query = "UPDATE property SET name = ?, size = ?, type_picture = ?, file_path = ?, username = ?
WHERE address = ? AND city = ?"
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username,$address,$city);
if (!$conn->execute()) {
echo 'error update';
}
}
You need an AND or OR in the WHERE statement:
WHERE address = '$address' AND // with our without ''
city = '$city' ";
I also don't think you should mix parameters with string substitution. Make $address and $city parameters as well.

Categories