mysql_num_rows comparison operator - mysql

Edit Note: There was nothing wrong with this comparison operator. I was asked to expound, so added the code below. As it turned out, the problem was in the UniqueID function I was using to create a unique string.
I'm trying to troubleshoot an intermittent problem in a database save. Basically, the code does an earlier query with posted data. I then check the number of rows in that query to determine whether to update or insert the record.
About 1% of the time, this doesn't work, and an unrelated record is overwritten. I'm wondering if, perhaps there is something wrong with the comparison operator I am using with mysql_num_rows().
Are there any possible odd effect with using
if(mysql_num_rows($Result) != 0)
ADDED LATER:
mysql version 5.0.51a
I will try my best to explain what is important here.
The tables are involved in an in-house credit application. The salesperson fills out a form for the company applying for the credit. They can then save that application to complete later or send off to the accounting dept for approval. The accountant can save the record for later, return it to the salesperson, or approve it. In any of these operations the entire form is either inserted (when first created) or updated in the table record.
When any operations that transfer the access to the form to the salesperson or accountant, an e-mail is sent to the appropriate party, which includes a link to the record. The salesperson only has access to the records they have created. This is done by simply checking their login username, held in a session variable, with a field in the table that also holds their username.
At the top of the form is a select box that holds records waiting to be processed. What is available for the salesperson in that box is records he/she has stored or records sent back to him/her for corrections and re-submission. They can pull up a form by simply selecting one. They can also retrieve a form by clicking on the e-mail link, sent to them when they submit a form or the admin (accountant) returns a form to them. Likewise, the accountant can do the same, by both methods, with records sent to them to process.
Each transaction in this process in logged in a Transaction Detail Table.
There are many error checks that prevent a record from being accessed inappropriately. (Bear with me, this is all important) Salesperson and Accountant do not have access to the record at the same time and, once an application is approved, neither have access except to view.
The Problem
Everything is dependent on the ID field, which is an auto-increment mysql field in the CreditApp table. This number is stored in the log file in the "AppID" field. In about 1% of these transactions, either when the salesperson submits the form to the admin (accountant) or the accountant approves it, rather than updating the correct record, a completely unrelated record is updated. Each overwritten record is a record that has been previously processed (meaning "approved" by the accountant). Very often, but not necessarily, the record that is overwritten can be a year or two old.
Although I'm not sure whether the record is overwritten on submit by the salesperson or on approval by the admin, the other peculiar thing is that, when this overwrite happens, the entries in the log table, on submit by the salesperson, do not have the AppID that relates them to the form record. It is blank.
So here is a very simplified mock up of the process (I am sure there is a much more eloquent way to do this but alas...):
if($Process == "RegularSave") // Salesperson storing record for later
{
$Status = "Store";
$StoreTitle = $NewTitle;
if(empty($StoreTitle)){$Error[] = "Title cannot be blank. Record was not saved!";}
$Q = "SELECT ID, StoreTitle FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'"; // UniqueID prevents double entry on refresh of new record
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in storage result!";}
}
elseif($Process == "RegularSubmit") //Sslesperson submitting record
{
$Status = "Received";
$StoreTitle = $NewTitle;
if(empty($StoreTitle)){$Error[] = "Title cannot be blank. Record was not saved!";}
$Q = "SELECT ID FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'"; // UniqueID prevents double entry on refresh of new record
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in ID Check!";}
}
elseif($Process == "AdminProcess" || $Process == "AdminSave" || $Process == "AdminReturn")
{
// Status variable set here as to "Revised", "Rejected", "Approved", etc.
// THEN:
$Q = "SELECT ID FROM CreditApp WHERE ID = '$ID'";
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in ID Check!";}
}
elseif($Process == "AdminSend")
{
// Setup for e-mail from admin when returning record for corrections
$ReturnDate = dFormat($Time,41);
$FromName = $AdminName;
$FromEmail = $AdminAddress;
$ReturnUser = $_SESSION['FullName'];
$DetailMsg = nl2br($Message);
$NoteString = '======================='."\n".$ReturnUser.': '.$Today."\n".$Message."\n".'======================='."\n".$Notes;
$R = mysql_query("UPDATE CreditApp SET Notes = '$NoteString', Status = 'Return', ReturnDate = '$ReturnDate', ReturnUser = '$ReturnUser', AdminID = '$_SESSION[User]' WHERE ID = '$ID'");
$M = mysql_query("INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser) VALUES ('$ID','Return for Corrections','$DetailMsg','$FormName','$_SESSION[User]')");
$HTMLData = ('Your credit request for '.$AcctName.' has been returned for the following reasons:<br /><br />'.nl2br($Message).'<br /><br />
FormLink: You can access the record from this link.<br />
You will also find it available in your stored records list at the top of the Credit Application Request form.
<br /><br />');
}
if(count($Error) == 0 && $Process != "AdminSend")
{
if(mysql_num_rows($Result) != 0) // Indicates record already exists
{
#=====================================================#
# Update Existing Record #
#=====================================================#
$X = mysql_fetch_array($Result);
$Q = "UPDATE CreditApp ... WHERE ID = '$X[ID]'"; // Standard Update set of fields
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database update error! (1) ApproveDate: ".$ApproveDate.' '.mysql_error();}
else
{
// Here related tables are updated (simple one-to-many relationships for form data)
// THEN:
#=====================================================#
# Log any changes #
#=====================================================#
$LQ = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName',";
if($AppType == "New"){$ApprovalString = $Approval;}
elseif($Approval == "Approved"){$ApprovalString = "Completed";} // Revised entry
else{$ApprovalString = $Approval;}
if($_SESSION[GVars][Approval] != $Approval || $AppType == "Revised")
{
$StatusString = $Status.'/Credit';
$LQ .= " Status = '$StatusString', CreditApproval = '$ApprovalString', CreditDate = '$ThisDate',";
}
$TAction=array(); $TDetail=array();
if($_SESSION[GVars][SubmitDate] != $SubmitDate)
{
$TAction[] = 'Form Submitted';
$TDetail[] = $AppType != "Revision" ? "Credit Application submitted for approval" : "Credit Revision Request submitted";
$LQ .= " SubmitDate = '$SubmitDate'";
}
if($_SESSION[GVars][Approval] != $Approval || $_SESSION[GVars][SubmitDate] != $SubmitDate || $AppType == "Revised")
{
if(substr($LQ,-1) == ','){$LQ = substr($LQ,0,-1);}
$LQ .= " WHERE AppID = '$ID'";
$Result = mysql_query($LQ);
if(!$Result){$Error[] = "Log File Error! [1] ".mysql_error();}
}
if($_SESSION[GVars][Approval] != $Approval || $AppType == "Revised")
{
if($AppType != "Revised")
{
if($Approval == "Approved")
{
$TAction[] = '<span class="LogBlue">Credit Application Approved</span>'; $TDetail[] = 'This Credit Application has been approved for '.$CreditAmt;
}
elseif($Approval == "Declined")
{
$TAction[] = '<span class="LogRed">Credit Application Declined</span>'; $TDetail[] = 'This Credit Application has been declined';
}
}
else
{
if($Approval == "Approved")
{
$TAction[] = '<span class="LogBlue">Credit Revision Approved</span>'; $TDetail[] = 'This submitted credit revision has been approved and completed.';
}
elseif($Approval == "Rejected")
{
$TAction[] = '<span class="LogRed">Credit Revision Rejected</span>'; $TDetail[] = 'This Credit Revision has been rejected';
}
}
}
if($_SESSION[GVars][Status] != $Status)
{
$TAction[] = 'Status Change';
if(!empty($_SESSION[GVars][Status]))
{
$TDetail[] = 'Status change from '.$_SESSION[GVars][Status].' to '.$Status;
}
else
{
$TDetail[] = 'Status change set to '.$Status;
}
}
if($_SESSION[GVars][StoreTitle] != $StoreTitle)
{
$TAction[] = 'Store Title Change';
if(empty($_SESSION[GVars][StoreTitle]))
{
$TDetail[] = 'Store Title created: '.$StoreTitle;
}
else
{
$TDetail[] = 'Store Title change from '.$_SESSION[GVars][StoreTitle].' to '.$StoreTitle;
}
}
$TranCount = count($TAction);
for($a=0;$a<$TranCount;$a++)
{
$Q = "INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser) VALUES ('$ID','$TAction[$a]','$TDetail[$a]','$FormName','$_SESSION[FullName]')";
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Log File Error! [2]";}
if($Status == "Processed")
{
$Q = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName', CreditDate = CURDATE(), Date = NOW(), AdminUser = '$_SESSION[User]' WHERE AppID = '$ID'";
}
else
{
$Q = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName', Date = NOW() WHERE AppID = '$ID'";
}
$Result = mysql_query($Q);
}
switch($Process)
{
// Text is set here to display result and status to the user
}
}
}
elseif(!$_SESSION['Admin']) // Record is new entry. Admin only deals with records in process
{
#=====================================================#
# Create New Record #
#=====================================================#
$Q = "INSERT INTO CreditApp ..."; // Standard Insert set of fields
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Error in database insert! (1) ".mysql_error($Conn);}
else
{
// Here related tables are updated (simple one-to-many relationships for form data)
// THEN:
#=====================================================#
# Create new Log Entry #
#=====================================================#
$CreditApproval = !empty($Approval) ? $Approval : "";
if(!empty($ApproveDate)){$CreditDate = $ApproveDate;}
if(!empty($DeclineDate)){$CreditDate = $DeclineDate;}
if($Process == "RegularSave")
{
if($AppType != "Revision")
{
$Action = "Record Created";
$Detail = "A new record was created but stored to submit at a later date.";
$StatusString = "Store/Credit";
}
else
{
$CreditApproval = "Current";
$Action = "Credit Revision";
$Detail = "A Credit Revision was created but stored to submit at a later date.";
$StatusString = "Store/Credit";
}
}
elseif($Process == "RegularSubmit")
{
if($AppType != "Revision")
{
$Action = "Record Created";
$Detail = "A new record was created and sent to Administration for approval.";
$StatusString = "Received/Credit";
}
else
{
$CreditApproval = "Current";
$Action = "Credit Revision";
$Detail = "A Credit Revision was sent to Administration.";
$StatusString = "Received/Credit";
}
}
else
{
$Action = "Error!";
if(empty($Process)) // "Detail text added 2/19/15 (Previously was blank)
{
$Detail = "Process variable is empty";
}
else
{
$Detail = $Process.' should equal RegularSave or RegularSubmit';
}
}
if(empty($CreditDate)){$CreditDate = "0000-00-00";}
if(empty($SubmitDate)){$SubmitDate = "0000-00-00";}
$Result = mysql_query("INSERT INTO CustAcctStats (AppID,AppType,User,StoreTitle,Company,Status,CreditApproval,CreditDate,SubmitDate,Date)
Values ('$ID','$AppType','$_SESSION[User]','$StoreTitle','$AcctName','$StatusString','$CreditApproval','$CreditDate','$SubmitDate',NOW())");
if(!$Result){$Error[] = "Log File Error! [3] ".mysql_error();}
else
{
$Result = mysql_query("INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser,TranDate) VALUES ('$ID','$Action','$Detail','$FormName','$_SESSION[FullName]',NOW())");
if(!$Result){$Error[] = "Log File Error! [4]";}
}
}
}
elseif($_SESSION['Admin'])
{
$Error[] = "Record not found!<br />Please exit Admin mode if you want to save a new record!";
}
}
if(($_POST['Submit'] == "Submit" || $Process == "AdminSend" || $Process == "AdminProcess") && count($Error) == 0)
{
// Here the e-mail is generated
}

You are using InnoDB, correct? And you have multiple connections possibly doing queries like this? But you don't don't have BEGIN...COMMIT around the pair (SELECT, INSERT/UPDATE) of statements?
Switch to INSERT ... ON DUPLICATE KEY UPDATE ... in order to do the process in a single, atomic, operation.
If you do have BEGIN...COMMIT, does the SELECT have FOR UPDATE on the end? It should -- in order to lock the record that needs UPDATEing or lock the spot where the new record will be INSERTed.

SELECT ID, StoreTitle FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'
That probably performs very slowly. Check the EXPLAIN or time it. The workaround is to turn it into a UNION:
( SELECT ID, StoreTitle CreditApp WHERE ID = '$ID' )
UNION DISTINCT
( SELECT ID, StoreTitle CreditApp WHERE UniqueID ='$UniqueID' )
I don't see where $R (the INSERT?) or $M (the UPDATE?) are being executed. How long does it take between the SELECT and the INSERT/UPDATE? The longer that timespan, the more chance of another connection slipping in.
Furthermore if that OR is slow, you could have multiple SELECTs queued up, waiting to sneak in. And a SELECT without an OR can slip in very fast.
As I understand it, you really need the LOCK TABLES WRITE... before the SELECT and UNLOCK TABLES after the INSERT/UPDATE. Otherwise, as you have seen, occasionally, things mess up.
Or, skip the LOCK/UNLOCK and turn the INSERT/UPDATE into INSERT...ON DUPLICATE KEY UPDATE, since it is atomic. (Even if the SELECT is kept, and even if it goofs, the IODKU will correct for it.)

Related

Having issue while updating the records in laravel it is showing page not found

I have three table accidents, vehicle and people. I am performing curd operation but I am not able to update as there are multiple rows and columns. Can you please check the routes and actually idk the correct way of updating
public function edit($id)
{
$resultset = DB::select('select * from accidents where id = ?',[$id]);
$vehicle = DB::table('vehicle')
->select(['vehicle.type', 'vehicle.details', 'vehicle.vehicleno', 'people.age', 'people.gender', 'people.status'])
->join('people','people.vehicle_id','=','vehicle.id')
->where('people.accidents_id','=',$id)
->get();
return view('updaterecord', array('accident'=>$resultset,'vehicle'=>$vehicle));
}
public function update($id)
{
$branch = $request->input('branch');
$roadname = $request->input('roadname');
$caseregister = $request->input('casereg');
$description = $request->input('description');
$ipc_mvact =$request->input('ipc_mvact');
$type = $request->input('vehicletype');
$vehicleno = $request->input('vehicleno');
$vehicledetails = $request->input('vdetails');
$age=$request->input('age');
$gender=$request->input('gender');
$status=$request->input('status');
DB::update('update acidents set branch = ?, roadname=? ,casereg=?, description=?, IPC_MVAct_Sections=? where id = ?',[$branch,$roadname,$caseregister,$description, $ipc_mvact,$id]);
DB::update('update vehicle set type = ?, vehicleno=? ,vehicledetails=? where accidents_id = ?',[$type,$vehicleno,$vehicledetails,$id]);
DB::update('update people set age = ?, gender=? ,status=? where accidents_id = ?',[$age,$gender,$status,$id]);
return redirect('/admin/tables');
}
// Routes
Route::namespace('Auth')->group(function () {
Route::get('/login', '\App\Http\Controllers\AdminController#index');
Route::post('/admin', '\App\Http\Controllers\AdminController#checklogin');
Route::get('/admin/dashboard', '\App\Http\Controllers\AdminController#successlogin');
Route::get('/admin/tables', '\App\Http\Controllers\AdminController#showtable');
Route::get('/admin/tables/viewrecord/{id}', '\App\Http\Controllers\AdminController#viewaccident');
Route::get('/admin/tables/editrecord/{id}', '\App\Http\Controllers\AdminController#edit');
Route::post('/admin/tables/edit/{id}', '\App\Http\Controllers\AdminController#update');});
//form
<form action="/edit/<?php echo $accident[0]->id; ?>" method="POST">
You have error in action url .so for better usage i have added named route for updates like below
Route::post('/admin/tables/edit/{id}', '\App\Http\Controllers\AdminController#update')->name('adminUpdate');
in your form action
<form action="{{route('adminUpdate',[$accident[0]->id])}}" method="POST">

MYSQL ON DUPLICATE KEY UPDATE not working as intended [duplicate]

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 2 years ago.
My app automatically checks when the customer logs in and only gives back one access_token and one shop values.
Below is the table with headings and a row of example data
access_token
shop
111111111
shop1
Sometimes a new customer installs the app and a new shop and access_token is created and I need to INSERT all new data in each column.
Other times the customer has re-installed the app so the shop exists but the access_token has changed and I need to update it.
How do I INSERT if none exist, but UPDATE if a value (shop) exists and another (access_token) doesn't when I am only given a single value of each?
I have attempted with ON DUPLICATE KEY UPDATE below where the shop is the same but the access_token has changed, but because I only get given one access_token to check when the customer logs in to the app it would just insert and not update.
INSERT INTO customers (access_token, shop)
VALUES(111, "shop1")
ON DUPLICATE KEY UPDATE access_token=111
I have attempted an example below where the shop is the same but the access_token has changed, however, I keep getting syntax errors. Please help, thank you.
SELECT EXISTS(SELECT shop FROM customers WHERE shop = 'shop1') AS sp,
NOT EXISTS (SELECT access_token FROM customers WHERE access_token = '{999999999}') AS tk
IF sp AND tk = 1
UPDATE customers
SET access_token='999999999'
WHERE shop = 'shop1';
ELSEIF NOT EXISTS (SELECT shop FROM customers WHERE shop = 'shop1') THEN
INSERT INTO customers (access_token, shop)
SELECT * FROM (SELECT '999999999', 'shop1') AS tmp;
END IF;
Are you using purely MySQL? I have made a signup and login page before as part of a web app and used Php to do this. I believe you can use Php for apks so I will write in Php, but you should be able to translate to your language with ease.
<?php
if (isset($_POST['signup-submit'])) { //this is so that the following can only be done on
the button press (name of it is signup-submit)
require 'dbh.inc.php';
$username = $_POST['Username'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$confirmpassword = $_POST['cpwd']; //this is all off the details of the user passed
through to be run through this script into the
database
if (empty($username) || empty($email) || empty($password) || empty($confirmpassword)) {
header("Location: ../index.php?error=emptyfields&uid=". $username. "&mail=". $email);
exit();
} //checking for empty fields
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invalidemail&uid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidemailuid");
exit();
}
else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invaliduid&email=". $email);
exit();
}
else if ($password !== $confirmpassword) {
header("Location: ../index.php?error=checkpasswords&mail=".$email. "&uid=".$username);
exit();
} //checking all characters used are only that which you allow
else {
$sql = "SELECT uidusers FROM users WHERE uidusers=?";
$sqly = "SELECT emailusers FROM users WHERE emailusers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
} //using prepared statements to insert user info
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../index.php?error=usertaken&mail=". $email);
exit();
} //checking for existing details
if (!mysqli_stmt_prepare($stmt, $sqlx)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sqly)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck3 = mysqli_stmt_num_rows($stmt);
if ($resultCheck3 > 0) {
header("Location: ../index.php?error=emailtaken");
exit();
} //storing details
else {
$sql = "INSERT INTO users (uidusers, emailusers,
pwdusers, invcode) VALUES (?, ?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT); //hashing passwords
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedpwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success"); //all details stored successfully
As for your access token, I would suggest adding a function to run a uniqid() function along with another function to check for existing tokens so that duplicates aren't made ( I did this for another similar reason to yours) and then using similar code as above to write that in.
I'm not sure what your shop ID is for but I have options for 2 eventualities:
If it's just a sort of ID, auto increment it in the database
If it's to show which shop the person entered, use foreign keys to link the column to a parent table with all the shops listed and set the relationship to cascade. Then make a button to switch shops that will
A) send an update to the database, overwriting the child column and row of the user
B) redirect the user to the new shop
(I have no idea why the second half of the code is green, but if you remove my comments you should be good, though I'd advise you to write your own code so that you can see how it works and adapt it to your own project)

How to get last inserted id with insert method in laravel

In my laravel project I am inserting multiple records at time with modelname::insert method. Now I want to get last inserted id of it.I read somewhere when you insert multiple records with single insert method and try to get the last_record_id it will gives you the first id of the last inserted query bunch. But my first question is how to get last record id with following code .If I am able to get first id of the bunch .I ll make other ids for other record by my own using incremental variable.
Code to insert multiple record
if(!empty($req->contract_name) && count($req->contract_name)>0)
{
for($i=0; $i<count($req->contract_name); $i++)
{
$contract_arr[$i]['client_id'] = $this->id;
$contract_arr[$i]['contract_name'] = $req->contract_name[$i];
$contract_arr[$i]['contract_code'] = $req->contract_code[$i];
$contract_arr[$i]['contract_type'] = $req->contract_type[$i];
$contract_arr[$i]['contract_ext_period'] = $req->contract_ext_period[$i];
$contract_arr[$i]['contract_email'] = $req->contract_email[$i];
$contract_arr[$i]['created_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['updated_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['created_by'] = Auth::user()->id;
$contract_arr[$i]['updated_by'] = Auth::user()->id;
if($req->startdate[$i] != ''){
$contract_arr[$i]['startdate'] = date('Y-m-d',strtotime($req->startdate[$i]));
}
if($req->enddate[$i] != ''){
$contract_arr[$i]['enddate'] = date('Y-m-d',strtotime($req->enddate[$i]));
}
}
if(!empty($contract_arr)){
Contract::insert($contract_arr);
}
}
You should be able to call it like this
$lastId = Contract::insert($contract_arr)->lastInsertId();
If i see right, you're using a Model. Direct inserting only shows an success boolean. Try this instead:
Contract::create($contract_arr)->getKey()

MySQL and using only some results

I am trying to create a directory and having an issue calling the "listing image" in the results. The issue is that only some listings will have images, otherwise if they do not, I want them to use the default-image I have set up. When I try and add in the 'image' table to my query, it returns ONLY the results that have an image available (leaving out the other listings that do not have an image).
Here is my code:
public function search($neighborhood = null, $biz_filter = null) {
$neighborhood = $this->uri->segment(3);
$biz_filter = $this->uri->segment(4);
// SELECT
$this->db->select('*');
// MAIN TABLE TO GRAB DATA
$this->db->from('biz');
// TABLES TO JOIN
$this->db->join('city', 'city.city_id = biz.biz_cityID');
$this->db->join('zip', 'zip.zip_id = biz.biz_zipID', 'zip.zip_cityID = city.city_id');
$this->db->join('state', 'state.state_id = city.city_stateID');
$this->db->join('neighborhood', 'neighborhood.neighborhood_id = biz.biz_neighborhoodID');
$this->db->join('biz_filter', 'biz_filter.bizfilter_bizID = biz.biz_id');
$this->db->join('biz_category', 'biz_category.bizcategory_id = biz_filter.bizfilter_bizcategoryID');
if ($neighborhood != "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood != "-" AND $biz_filter == "-") {
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood == "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
} else {
}
// ORDER OF THE RESULTS
$this->db->group_by('biz_name asc');
// RUN QUERY
$query = $this->db->get();
// IF MORE THAN 0 ROWS ELSE DISPLAY 404 ERROR PAGE
return $query;
}
How can I add in the separate table, 'image' that holds the logo images ('image.image_file'). The 'image' table and 'biz' table are connected through the business ID i pass through each table (image.biz_id = biz.biz_id).
Anyone know how to resolve the query to work properly?
Just use
$this->db->join('image', 'image.biz_id = biz.biz_id', 'left');
To LEFT JOIN your image table. When there is no records in the table for the biz_id the image.image_file will have null values. Read here for more information.
You can use a COALESCE function to replace the "null" images with a predefined default value. Just replace your line with $this->db->select('*'); to this one:
// SELECT
$this->db->select("*, COALESCE(image.image_file, 'images/not_found.png') as my_image_file");
When you render the output make sure you use my_image_file column for the image.
On a side note: avoid using '*' in the select. Select only those columns you actually need. Selecting all columns unnecessarily increases the load on the database server resources.

I can't find the solution in a SQL message. I would like some advice

I have a site www.jazz.eu.
I did an exact copy of this site to another with a different domain name, in a different server. The new one is www.vetur.nl.
Everything works fine (I mean similar to jazz.eu). Except the cart process.
First when I see the cart I always have a line with an empty product. I can't remove it. see what i mean
http://www.vetur.nl/cart_empty_product_line.jpg
and the next problem that i have is that when I try to refresh the cart or send the order I get this message
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'sender_full_name='',sender_afm='',sender_doy='',sender_work='',sender_person='',' at line 1
query=update basket set selected_quantity=,sender_full_name='' ,sender_afm='',sender_doy='',sender_work='',sender_person='',sender_address='',sender_zip='',sender_tel='',sender_fax='', addresser_email='', additional='' where session_id = 'ihcvafpk3fgqh6jra1mrplgkr1' and id=
I think the problem is in this file process.php but I can't find it. The exact file works fine in my first site jazz.eu. The code of process.php that seems that have problem is below.
Thank you and forgive any mistake in posting. It is the first time I post here.
function procMy_cart(){
global $session, $form,$database,$mailer;
$session_id = session_id();
if ((isset($_POST['order'])) && ($_POST['order']==1)) {
if (!eregi("[a-z\α-ω\!\"\£\$\%\^\&\*\(\)\-\+\{\}\:\;\'\#\~\#\\\|\<\>\?\/]", $_POST['update_quantity'][$i])) {
For ($i=0;$i<count($_POST['update_quantity']);$i++) {
if (!eregi("[a-z\α-ω\!\"\£\$\%\^\&\*\(\)\-\+\{\}\:\;\'\#\~\#\\\|\<\>\?\/]", $_POST['update_quantity'][$i])) {
//$update_db="update basket set selected_quantity=".$_POST['update_quantity'][$i].",addresser='".$_POST['addresser']."',addresser_tel='".$_POST['addresser_tel']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$update_db="update basket set selected_quantity=".$_POST['update_quantity'][$i].",sender_full_name='".$_POST['addresser']."',sender_afm='".$_POST['addresser_afm']."',sender_doy='".$_POST['addresser_doy']."',sender_work='".$_POST['addresser_work']."',sender_person='".$_POST['addresser_contact']."',sender_address='".$_POST['addresser_address']."',sender_zip='".$_POST['addresser_zip']."',sender_tel='".$_POST['addresser_tel']."',sender_fax='".$_POST['addresser_fax']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$result=$database->query($update_db);
} else {
//$update_db="update basket set selected_quantity=1,addresser='".$_POST['addresser']."',addresser_tel='".$_POST['addresser_tel']."',addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$update_db="update basket set selected_quantity=1,sender_full_name='".$_POST['addresser']."',sender_afm='".$_POST['addresser_afm']."',sender_doy='".$_POST['addresser_doy']."',sender_work='".$_POST['addresser_work']."',sender_person='".$_POST['addresser_contact']."',sender_address='".$_POST['addresser_address']."',sender_zip='".$_POST['addresser_zip']."',sender_tel='".$_POST['addresser_tel']."',sender_fax='".$_POST['addresser_fax']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$result=$database->query($update_db);
}
}
}
// $retval = $session->my_cart($_POST['addresser'], $_POST['addresser_doy'], $_POST['addresser_work'], $_POST['addresser_afm'], $_POST['addresser_address'], $_POST['addresser_zip'], $_POST['addresser_contact'], $_POST['addresser_email'], $_POST['addresser_tel'], $_POST['addresser_fax'], $_POST['additional']);
// if ($retval) {
// $_SESSION['send_order'] = true;
// header("Location: my_cart2.php");//.$session->referrer);
// } else {
// $_SESSION['value_array'] = $_POST;
// $_SESSION['error_array'] = $form->getErrorArray();
// header("Location: my_cart2.php");//.$session->referrer);
// }
header("Location: order2.php");
} else if ((isset($_POST['order'])) && ($_POST['order']!=1)) {
if ((isset($_POST['refresh_basket'])) && ($_POST['refresh_basket']==1)) {
For ($i=0;$i<count($_POST['update_quantity']);$i++) {
//echo $_POST['update_id'][$i];
if (!eregi("[a-z\α-ω\!\"\£\$\%\^\&\*\(\)\-\+\{\}\:\;\'\#\~\#\\\|\<\>\?\/]", $_POST['update_quantity'][$i])) {
//$update_db="update basket set selected_quantity=".$_POST['update_quantity'][$i].", addresser='".$_POST['addresser']."', addresser_tel='".$_POST['addresser_tel']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$update_db="update basket set selected_quantity=".$_POST['update_quantity'][$i].",sender_full_name='".$_POST['addresser']."',sender_afm='".$_POST['addresser_afm']."',sender_doy='".$_POST['addresser_doy']."',sender_work='".$_POST['addresser_work']."',sender_person='".$_POST['addresser_contact']."',sender_address='".$_POST['addresser_address']."',sender_zip='".$_POST['addresser_zip']."',sender_tel='".$_POST['addresser_tel']."',sender_fax='".$_POST['addresser_fax']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$result=$database->query($update_db);
} else {
//$update_db="update basket set selected_quantity=1, addresser='".$_POST['addresser']."', addresser_tel='".$_POST['addresser_tel']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$update_db="update basket set selected_quantity=1,sender_full_name='".$_POST['addresser']."',sender_afm='".$_POST['addresser_afm']."',sender_doy='".$_POST['addresser_doy']."',sender_work='".$_POST['addresser_work']."',sender_person='".$_POST['addresser_contact']."',sender_address='".$_POST['addresser_address']."',sender_zip='".$_POST['addresser_zip']."',sender_tel='".$_POST['addresser_tel']."',sender_fax='".$_POST['addresser_fax']."', addresser_email='".$_POST['addresser_email']."', additional='".$_POST['additional']."' where session_id = '$session_id' and id=".$_POST['update_id'][$i]."";
$result=$database->query($update_db);
}
}
}
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: my_cart2.php");//.$session->referrer);
}
} // end cart
The variable $_POST['update_quantity'][$i] doesn't have a value. If you look at the query you'll notice set selected_quantity=,sender_full_name=''. You need at least a set of single quotes or null assigned to selected_quantity.
You should never assign _POST data directly into a query. Always scrub it somehow to avoid SQL Injection attacks. You shold probably assign $_POST['update_quantity'][$i] to a variable early on and perform some logic to ensure it has a valid value and if not, either prevent the query from running or add a default value.