I need to find duplicated details in the existing table while uploading a Excel file that contains some details,i need to find that by phone number and customer name. I am using mattexcel to upload the data into database.
I don't want to insert that details if it is in there but other details must insert into that table
Controller
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
$data['customername'] = $row['customername'];
$data['chassis'] = $row['chassis'];
$data['model'] = $row['model'];
$data['branchcode'] = $row['branchcode'];
$data['delivery'] = $row['delivery'];
$data['customerid'] = $row['customerid'];
$data['phone'] = $row['phone'];
$data['invoicedate'] = $row['invoicedate'];
$data['dse'] = $row['dse'];
$data['branch'] = $row['branch'];
$data['finance'] = $row['finance'];
$data['dono'] = $row['dono'];
$data['invoice'] = $row['invoice'];
$data['zsm'] = $row['zsm'];
$data['sm'] = $row['sm'];
$data['agm'] = $row['agm'];
$data['dsecode'] = $row['dsecode'];
$data['address'] = $row['address'];
$data['email'] = $row['email'];
$data['color'] = $row['color'];
$data['extendedwarrenty'] = $row['extendedwarrenty'];
$data['autocaddownload'] = $row['autocaddownload'];
$data['numberplate'] = $row['numberplate'];
$data['mcpstatus'] = $row['mcpstatus'];
$data['plandt'] = $row['plandt'];
$data['planok'] = $row['planok'];
$data['fasttag'] = $row['fasttag'];
// $data['settilment_pdf_path'] = $row['settilment_pdf_path'];
$data['rcstatus'] = $row['rcstatus'];
$branch = Branch::where([['branch_code', $row['branchcode']], ['status', 0]])->first();
$registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();
if (count($registration_id) > 0) {
$regid = $registration_id[0]->registration_id;
$regid = $regid + 1;
} else {
$regid = 1;
}
$register = new Registration();
$register->registration_id = $regid;
$register->customername = $row['customername'];
$register->chassis = $row['chassis'];
$register->model = $row['model'];
$register->branchcode = $row['branchcode'];
$register->delivery = $row['delivery'];
$register->customerid = $row['customerid'];
$register->phone = $row['phone'];
$register->invoicedate = $row['invoicedate'];
$register->dse = $row['dse'];
$register->branch = $row['branch'];
$register->finance = $row['finance'];
$register->dono = $row['dono'];
$register->invoice = $row['invoice'];
$register->zsm = $row['zsm'];
$register->sm = $row['sm'];
$register->agm = $row['agm'];
$register->dsecode = $row['dsecode'];
$register->address = $row['address'];
$register->email = $row['email'];
$register->color = $row['color'];
$register->extendedwarrenty = $row['extendedwarrenty'];
$register->autocaddownload = $row['autocaddownload'];
$register->numberplate = $row['numberplate'];
$register->mcpstatus = $row['mcpstatus'];
$register->plandt = $row['plandt'];
$register->planok = $row['planok'];
$register->fasttag = $row['fasttag'];
$register->rcstatus = $row['rcstatus'];
$register->dealership = $branch->dealership_id;
$register->zone = $branch->zone_id;
$register->dh = $branch->dh_id;
$register->status = '0';
$register->created_user_id = Session::get('created_id');
$register->save();
$regidn = Registration::orderBy('registration_id', 'desc')->get();
$regidd = $regidn[0]->registration_id;
$ssitrack = new Ssi_track();
$ssitrack->registration_id = $regid;
$ssitrack->ssi_track_id = $regid;
$ssitrack->save();
$ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
$ssitrackk = $ssitrackk[0]->registration_id;
}
});
}
return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
}
Option 1. You can add unique values combination in migration.
Schema::table('your_table_name', function (Blueprint $table) {
$table->unique(['phone ','customername ']);
});
This won't let you insert same combination values for these column combination, however it also throws error stopping you import function.
Option 2 (Better).
Check if value already exits and ignore import for that column.
$old_customer = Regiter::where('phone', $row['phone'])->where('customername', $customername )->first();
//Inser only if customer not found
if(is_null($old_customer))
{
//INSERT QUERY
}
To decrease number of query you can pluck name and phone with single query or use any other optimization tricks.
Related
I am building chats pop up where one user will initiate conversation with another user.
In my initiatechat function i have the following error Call to undefined method stdClass::save().
Look at codes and find THIS SAVE FUNCTION ==>> the save() function that throw error.
If two users have already initiated conversation this error does not happen.
public function actionInitiatechat() {
if (isset($_POST)){
//$message = Myclass::checkPostvalue($_POST['message']) ? $_POST['message'] : "";
$senderId = Myclass::checkPostvalue($_POST['sender']) ? $_POST['sender'] : "";
$receiverId = Myclass::checkPostvalue($_POST['receiver']) ? $_POST['receiver'] : "";
$messageType = Myclass::checkPostvalue($_POST['messageType']) ? $_POST['messageType'] : "";
$sourceId = Myclass::checkPostvalue($_POST['sourceId']) ? $_POST['sourceId'] : "";
$timeUpdate = time();
$message = $_POST['message'];
$Products = Products::model()->findByPk($sourceId);
if(isset($Products) && $Products->approvedStatus == 0)
{
echo "error";
}
else
{
$criteria = new CDbCriteria;
$criteria->condition = "(user1 = '$senderId' AND user2 = '$receiverId') OR (user1 = '$receiverId' AND user2 = '$senderId')";
$chatModel = Chats::model()->find($criteria);
$encodeMsg = urlencode($message);
if (empty($chatModel)){
$newChat = new Chats();
$newChat->user1 = $senderId;
$newChat->user2 = $receiverId;
$newChat->lastMessage = $encodeMsg;
$newChat->lastToRead = $receiverId;
$newChat->lastContacted = $timeUpdate;
$newChat->save();
$criteria = new CDbCriteria;
$criteria->condition = "(user1 = '$senderId' AND user2 = '$receiverId') OR (user1 = '$receiverId' AND user2 = '$senderId')";
$chatModel = Chats::model()->find($criteria);
}
$chatModel->lastContacted = $timeUpdate;
if ($chatModel->user1 == $senderId){
$chatModel->lastToRead = $chatModel->user2;
}else{
$chatModel->lastToRead = $chatModel->user1;
}
$chatModel->lastMessage = $encodeMsg;
THIS SAVE FUNCTION ==>> $chatModel->save();
$messageModel = new Messages();
$messageModel->message = $encodeMsg;
$messageModel->messageType = $messageType;
$messageModel->senderId = $senderId;
$messageModel->sourceId = $sourceId;
$messageModel->chatId = $chatModel->chatId;
$messageModel->createdDate = $timeUpdate;
$messageModel->save();
}
echo "success";
}
}
else
{
echo "failed";
}
}
The statement below is presumably returning a "bare" object of type stdClass, which doesn't define a save() method, hence your error.
$chatModel = Chats::model()->find($criteria);
Run var_dump($chatModel); immediately after this statement and see what type of object you're getting.
So I want to update my data in database, and I wanna make sure that the row it updates (which is the last name) is the same as the one logged in. I did is this:
'data' is the name of the table where the logged in last name is to be found, 'ict' is the table where the grades is in and another last name to so that i can compare if they're the same and update that row.
After I input the datas and confirm it, it says "Successfully Inserted" but the data doesn't get updated and it turns to 1.
This is my code:
<?php
include("sq.php");
$a21st = isset(($_POST['a21st']));
$a21st2 = isset(($_POST['a21st2']));
$entre = isset(($_POST['entre']));
$entre2 = isset(($_POST['entre2']));
$pe3 = isset(($_POST['pe3']));
$pe32 = isset(($_POST['pe32']));
$a1 = isset(($_POST['a1']));
$a12 = isset(($_POST['a12']));
$a2 = isset(($_POST['a2']));
$a22 = isset(($_POST['a22']));
$fil = isset(($_POST['fil']));
$fil2 = isset(($_POST['fil2']));
$mil = isset(($_POST['mil']));
$mil2 = isset(($_POST['mil2']));
$contem = isset(($_POST['contem']));
$contem2 = isset(($_POST['contem2']));
$physci = isset(($_POST['physci']));
$physci2 = isset(($_POST['physci2']));
$pe4 = isset(($_POST['pe4']));
$pe42 = isset(($_POST['pe42']));
$reaspro = isset(($_POST['reaspro']));
$reaspro2 = isset(($_POST['reaspro2']));
$a3 = isset(($_POST['a3']));
$a32 = isset(($_POST['a32']));
$a4 = isset(($_POST['a4']));
$a42 = isset(($_POST['a42']));
$immers = isset(($_POST['immers']));
$immers2 = isset(($_POST['immers2']));
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT =("SELECT * FROM data");
$result = mysqli_query($db,$SELECT);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$last = $row['last'];
$UPDATE = "UPDATE `ict` SET a21st = $a21st, a21st2 = $a21st2, entre= $entre, entre2 = $entre2, pe3 = $pe3, pe32 = $pe32, a1 = $a1, a12 = $a12, a2 = $a2, a22 = $a22, fil = $fil, fil2 = $fil2, mil = $mil, mil2 = $mil2, contem = $contem, contem2 = $contem2, physci = $physci, physci2 = $physci2, pe4 = $pe4, pe42 = $pe42, reaspro = $reaspro, reaspro2 = $reaspro2, a3 = $a3, a32 = $a32, a4 = $a4, a42 = $a42, immers = $immers, immers2 = $immers2 WHERE last = '".$last."'";
if (mysqli_query($db,$UPDATE)){
$message = "Successfully Inputted!!";
echo "<script type='text/javascript'>alert('$message');</script>";
}else {
echo "Error: <br>". $db->error;
}
}
$db->close();$db
isset returns true if the value exists, which translates to 1 in a numeric context, which is probably not what you meant. Instead, you need to get the value itself. E.g.:
$a21st = isset($_POST['a21st']) ? $_POST['a21st'] : null;
I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {
$wineID = $_POST["wineID"];
$wineCountryID = $_POST["wineCountryID"];
$wineSizeID = $_POST["wineSizeID"];
$wineRatingID = $_POST["wineRatingID"];
$wineColourID = $_POST["wineColourID"];
$packageID = $_POST["packageID"];
$wineCategoryID = $_POST["wineCategoryID"];
$wineCode = $_POST["wineCode"];
$price = $_POST["price"];
$description = $_POST["description"];
$wineRating = $_POST["wineRating"];
$wineIMG = $_POST["wineIMG"];
updateWine($updateWine);
$status = "$description has been updated.";
}
Update Wine Function
function updateWine($wineUpdate)
{
global $pdo;
$statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
WHERE wineID=?");
$statement->execute([$wineUpdate->wineID,
$wineUpdate->wineCountryID,
$wineUpdate->wineSizeID,
$wineUpdate->wineRatingID,
$wineUpdate->wineColourID,
$wineUpdate->packageID,
$wineUpdate->wineCategoryID,
$wineUpdate->wineCode,
$wineUpdate->price,
$wineUpdate->description,
$wineUpdate->wineRatingID,
$wineUpdate->wineIMG]);
$statement->fetch();
}
Something like the following should work for you:
function updateWine()
{
global $pdo;
$keys = [
"wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
"wineCode", "price", "description", "wineRating", "wineIMG",
];
$results = [];
foreach ($keys as $index) {
if (isset($_POST[$index])) {
$results[$index] = $_POST[$index];
}
}
$statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");
$statement->execute(array_merge(array_values($results), [$_POST['wineID']]));
$statement->fetch();
}
if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
updateWine();
}
Hope this helps!
if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
$result = updateWine($_POST);
if($result){
$status = "$description has been updated.";
}else{
$status = "An error occurred.";
}
}
//your function woud then look like ...
function updateWine($postdata){
$wineID = $postdata["wineID"];
$wineCountryID = $postdata["wineCountryID"];
$wineSizeID = $postdata["wineSizeID"];
$wineRatingID = $postdata["wineRatingID"];
$wineColourID = $postdata["wineColourID"];
$packageID = $postdata["packageID"];
$wineCategoryID = $postdata["wineCategoryID"];
$wineCode = $postdata["wineCode"];
$price = $postdata["price"];
$description = $postdata["description"];
$wineRating = $postdata["wineRating"];
$wineIMG = $postdata["wineIMG"];
//udpate your database with the above values
//check if update is successful
return true;
//else if there was an error
return false;
}
I want to insert JSON parameters in my phpmyadmin database. I tried with below code but it didn't work. Kindly help me in this.
my JSON parameters are:
`$ "address" = "bharuch"
"customer_id" = "108"
"products" = "[{"product_id":"1","product_name":"Potato","category_id":"1","subcategory_id":"1","product_memberprice":"11","product_nonmemberprice":"14","product_minquantity":"500 gms","product_image":"http:\/\/gaubharat.in\/gaubharat\/images\/potato.png","product_brand":"","sub_total":"28","user_qty":"2"},{"product_id":"2","product_name":"Tomato","category_id":"1","subcategory_id":"1","product_memberprice":"15","product_nonmemberprice":"18","product_minquantity":"500 gms","product_image":"http:\/\/gaubharat.in\/gaubharat\/images\/tomato.png","product_brand":"","sub_total":"18","user_qty":"1"}]"
"pincode" = "392025"
"order_totalamount" = "46"`
and my PHP code is:
<?php
require("config.inc.php");
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$product = json_decode($_POST['products']);
foreach( $product as $key => $val)
{
$product_id = $val['product_id'];
$product_name = $val['product_name'];
$category_id = $val['category_id'];
$subcategory_id = $val['subcategory_id'];
$product_memberprice = $val['product_memberprice'];
$product_nonmemberprice = $val['product_nonmemberprice'];
$product_minquantity = $val['product_minquantity'];
$product_image = $val['product_image'];
$product_brand = $val['product_brand'];
$sub_total = $val['sub_total'];
$user_qty = $val['user_qty'];
$query = "INSERT INTO `order`(cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address','$pincode',CURDATE())";
if(!mysqli_query($db,$query))
{
die('Error : ' . mysql_error());
}
else{
$response["success"] = 1;
$response["message"] = "You order placed successfully!";
echo json_encode($response);
}
}
?>
Kindly help me out in this.
You need to add json_decode function for $_POST['products'] as:
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$products = json_decode($_POST['products']);
foreach($products as $key => $val){
...
UPDATE 1:
You have an issue in your query. You are using 9 columns and insert 10 values.
$query = "INSERT INTO `order`(cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address',,'$pincode',NOW())";
What is this ,, after $address?
UPDATE 2:
Modified code:
<?php
require("config.inc.php");
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$product = json_decode($_POST['products']);
$values = array();
foreach($product as $key => $val)
{
$product_id = $val->product_id;
$product_name = $val->product_name;
$category_id = $val->category_id;
$subcategory_id = $val->subcategory_id;
$product_memberprice = $val->product_memberprice;
$product_nonmemberprice = $val->product_nonmemberprice;
$product_minquantity = $val->product_minquantity;
$product_image = $val->product_image;
$product_brand = $val->product_brand;
$sub_total = $val->sub_total;
$user_qty = $val->user_qty;
$values[] = "('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address','$pincode',CURDATE())";
}
if(count($values) > 0){
$query = "INSERT INTO `order` (cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ";
$query .= implode(",",$values);
if(!mysqli_query($db,$query))
{
echo "Error";
}
else
{
$response["success"] = 1;
$response["message"] = "You order placed successfully!";
echo json_encode($response);
}
}
?>
I'm building a website to learn PHP and have just built a membership app.
Here's my code to get the user cookies that I set when the user logs in, then take the business id they are associated with, called biz and look up all the details for the business with the id equal to biz, in the table named company: (btw, I know I'm using mysql but when I finalize my app, I'll switch to PDO or mysqli)
<?
$auth = $_COOKIE["auth"];
if ($auth != "1"){
header("Location: ./signin.php");
}
//Grab all the cookies
$firstname = $_COOKIE['firstname'];
$id = $_COOKIE['id'];
$fname = ucwords($_COOKIE['firstname']);
$lname = ucwords($_COOKIE['lastname']);
$email = $_COOKIE['email'];
$city = ucwords($_COOKIE['city']);
$biz = $_COOKIE['biz'];
if(!empty($biz)){
$donthaveabizyet = "false";
}
else{
include("./config.php");
$result = mysql_query("SELECT * FROM company WHERE id = '$biz'") or mysql_error();
while($row = mysql_fetch_array($result))
{
$business_name = $row['name'];
$business_phone = $row['phone'];
$business_website = $row['website'];
$business_phone = $row['phone'];
$business_cat1 = $row['cat1'];
$business_cat2 = $row['cat2'];
$business_cat3 = $row['cat3'];
$business_subcat1 = $row['subcat1'];
$business_subcat2 = $row['subcat2'];
$business_subcat3 = $row['subcat3'];
$business_email = $row['email'];
$business_product1 = $row['product1'];
$business_product2 = $row['product2'];
$business_product3 = $row['product3'];
$business_product4 = $row['product4'];
$business_product5 = $row['product5'];
$business_product6 = $row['product6'];
$business_product7 = $row['product7'];
$business_noaddress = $row['noaddress'];
$business_address = $row['address'];
$business_address2 = $row['address2'];
$business_zipcode = $row['zipcode'];
$business_city = $row['city'];
}
$result = mysql_query("SELECT * FROM company_secondary WHERE company_id = '$biz'") or mysql_error();
while($row = mysql_fetch_array($result))
{
$business_description = $row['company_description'];
$business_since = $row['phone'];
$business_logo = $row['logo'];
$business_since = $row['since'];
$business_smoking = $row['smoking'];
$business_delivery = $row['delivery'];
$business_alcohol = $row['alcohol'];
$business_kids = $row['kids'];
$business_wheelchair = $row['wheelchair'];
$business_twitter = $row['twitter'];
$business_facebook = $row['facebook'];
$business_youtube = $row['youtube'];
$business_creditcards = $row['creditcards'];
$business_outdoor = $row['outdoor'];
$business_featured = $row['featured'];
}
}
?>
Now I show a link to claim.php if the user's business id is equal to 0, or if the user's business id is set, I show the name of the business.
<?php
if($donthaveabizyet != "false")
{
echo "<br/><br/>You haven't claimed a business yet. <a href='claim.php'>Click here to claim one now.</a>";
}
else
{
echo $business_name;
}
?>
Unfortunately, $business_name isn't displaying, and the error is Notice: Undefined variable: business_name. Why is business_name not set?
Big thanks for all help!!
while($row = mysql_fetch_array($result))
{
is causing your problem. Change it to
while($row = mysql_fetch_assoc($result))
{
This is because fetch_array creates an array with numeric indexes ($array[1], $array[2], etc.). fetch_assoc makes the indexes the same as the column names ($array['this'], $array['that'], etc.)