I want to UPDATE a row in a table or INSERT it if it doesn't exist?
I have already read solution from this link. How do I UPDATE a row in a table or INSERT it if it doesn't exist?
So, i used replace but it did not work. It only added new row into the table but did not update anything.
this is my structure
<?php
define('ROOTPATH', __DIR__);
$output = [];
$output['result'] = [];
$output['image_path'] = [];
$applicationName = (isset($_POST) && array_key_exists('applicationName', $_POST)) ? $_POST['applicationName'] : 'applicationName';
if (empty($applicationName)) {
$output['result'][] = 'missing application name';
}
else if (is_array($_FILES) && array_key_exists('image', $_FILES) && array_key_exists('logo', $_FILES))
{
$upload_dir = '/upload_dir/';
$upload_path = ROOTPATH . $upload_dir;
$applicationName = $_POST['applicationName'];
$sql_field_list = ['applicationName'];
$sql_value_list = [$applicationName];
foreach ( $_FILES as $key => $upload) {
if($key != 'image' && $key != 'logo')
{
$output['result'][] = $key . ' is invalid image';
}
else
{
if ($upload['error'] == UPLOAD_ERR_OK &&
preg_match('#^image\/(png|jpg|jpeg|gif)$#', strtolower($upload['type'])) && //ensure mime-type is image
preg_match('#.(png|jpg|jpeg|gif)$#', strtolower($upload['name'])) ) //ensure name ends in trusted extension
{
$parts = explode('/', $upload['tmp_name']);
$tmpName = array_pop($parts);
$fieldname = ($key == 'image') ? 'bgBNPage' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["name"], PATHINFO_EXTENSION);
if (move_uploaded_file($upload["tmp_name"], $upload_path . $filename))
{
$sql_field_list[] = $fieldname;
$sql_value_list[] = $upload_dir . $filename;
$output['image_path'][$key] = $upload_dir . $filename;
}
else
{
$output['result'][] = $key . ' upload fail';
}
}
else
{
$output['result'][] = $key . ' error while upload';
}
}
}
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
$sql = "REPLACE INTO general (" . $fields . ") VALUES ('" . $values . "');";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
} else {
$output['result'][] = 'no file selected';
}
header('Content-type: application/json');
echo json_encode($output);
echo json_encode('finish');
?>
Can i use
if(logo or bgBNPage is enpty)
{
insert into database
}
else{
Update database
}
please tell me the correct syntax.
I'm guessing username is the field where, if it's a duplicate, you want to update. So, if username is a unique key, you can do something like:
insert into general ([fields]) values ([values])
on duplicate username update
[whatever]
I found the solution.
I use if else condition to proove it.
This is my code result
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
$sql = "SELECT logo,bgBNPage FROM general ";
$result = mysqli_query($con, $sql);
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
if(mysqli_num_rows($result) > 0)
{
$str_array = [];
for($i =0; $i < count($sql_field_list); $i++)
{
$str_array[] = $sql_field_list[$i] . "='" . $sql_value_list[$i] ."'";
}
$sql = 'UPDATE general SET ' . implode(',', $str_array);
//$sql = "UPDATE general SET (" . $fields . ") = ('" . $values . "');";
}
else
{
$sql = "INSERT INTO general (" . $fields . ") VALUES ('" . $values . "');";
}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
I am getting an error when tring to call a class
I have included the class in my Site Config File.
include($GLOBALS["webpath"] . "/classes/LM_com.php");
When i call for it I get An error that it cant be found. this is line 35
$loads = LM_com::GetLocationSearchCriteria($sql, $urlappend, "l");
error recieved
Fatal error: Class 'LM_com' not found in /home/{sitename}/public_html/pages/HotLoadSearchResults.php on line 35
Contents of the LM_com.php class
<?php
if (!defined("LM_NS_CLASSES_INCLUDED"))
{
define("LM_NS_CLASSES_INCLUDED", true);
define("HIDE_ORIGIN_CITY", (1 << 1));
define("HIDE_ORIGIN_ZIP", (1 << 2));
define("HIDE_DESTINATION_CITY", (1 << 3));
define("HIDE_DESTINATION_ZIP", (1 << 4));
define("HIDE_DESTINATION", (1 << 5));
define("ARCHIVE_POST", (1 << 6));
$GLOBALS["StatusMessages"] = array(
"Company Deleted.", // 0
"Company Activated.",
"Load Posted.", // 2
"Load Updated.",
"Load Deleted.", // 4
"Truck Posted.",
"Truck Updated.", // 6
"Truck Deleted.",
"User Deactivated.", // 8
"User Activated.",
"Passwords don't match.", // 10
"Password Changed.",
"User Deleted.", // 12
"Error Activating User.",
"Error Deactivating User.", // 14
"Error Deleting User.",
"News Posted.", // 16
"Error Posting News.",
"News Post Deleted.", // 18
"Error Deleting News Post.",
"User Profile Updated.", // 20
"Error Updating User Profile.",
"Company Profile Updated.", // 22
"Error Updating Company Profile.",
"User Moved.", // 24
"Error Moving User.",
"Error Adding User.", // 26
"User Added.",
"Company Added.", // 28
"Error Adding Company.",
"Email Sent.", // 30
"No Emails Sent.",
"Cannot Add Blacklisted Email Address.", // 32
"Bid Placed.",
"Bid Not Placed." // 34
);
class UserOwnedObject
{
var $UserID = -1;
// does this session's user own this object?
function IsUserOwner()
{
if ($this->UserID == -1)
return false;
if (!isset($_SESSION["user"]) || !$_SESSION["user"]->IsLoggedIn())
return false;
//if ($_SESSION["user"]->CheckPrivs("admin", "canDelete"))
// return true;
if ($this->UserID == $_SESSION["user"]->UserID)
return true;
return false;
}
}
function hex2asc($myin)
{
for ($i = 0; $i < strlen($myin) / 2; $i++)
{
$myout .= chr(base_convert(substr($myin, $i*2, 2), 16, 10));
}
return $myout;
}
// get the administrative email address for the site
// search order: config db, site-conf setting, Administrator user email address
function get_admin_email()
{
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$toaddr = "";
// try getting admin email from config table first
$sql = "SELECT ConfigValue FROM config WHERE ConfigName = 'admin_email'";
$conf = &$conn->Execute($sql);
if ($conf->RecordCount() > 0)
$toaddr = $conf->fields[0];
else if (!empty($GLOBALS["site_AdminEmail"])) // try falling back on site-conf setting
{
$toaddr = $GLOBALS["site_AdminEmail"];
}
else // last resort, look for a user named Administrator
{
// toaddr email address should come from username = 'Administrator'
$sql = "SELECT Email FROM users WHERE UserName = 'Administrator'";
$rs = &$conn->Execute($sql);
if ($rs === false)
die("internal error:" . $conn->ErrorMsg() . " SQL: " . $sql);
$toaddr = $rs->fields[0];
}
return $toaddr;
}
// this is a big chunk of search results code that's used for both loads & trucks
function GetEquipmentSearchCriteria(&$sql, &$urlappend, $prefix)
{
// if no equipment search options given, use 0 to mean any equipment matches
if (!isset($GLOBALS["EquipmentID"]) || empty($GLOBALS["EquipmentID"]))
$GLOBALS["EquipmentID"] = array();
// make the equipmentid list an array if it isn't one
if (!is_array($GLOBALS["EquipmentID"]))
$GLOBALS["EquipmentID"] = explode(",", $GLOBALS["EquipmentID"]);
$conn = &$GLOBALS["dbSettings"]->GetConnection();
// if there are any equipment search options, prepare the sql append
if (sizeof($GLOBALS["EquipmentID"]) > 0)
{
$gsql = "SELECT EquipmentID, SearchGroup FROM equipment WHERE EquipmentID IN (" . implode(",", $GLOBALS["EquipmentID"]) . ")";
$groups = $conn->Execute($gsql);
$search_ids = "";
while (!$groups->EOF)
{
if (!empty($search_ids))
$search_ids .= ",";
$search_ids .= $groups->fields[1];
$groups->MoveNext();
}
if (!empty($search_ids))
$sql .= " AND " . $prefix . ".EquipmentID IN ( " . $search_ids . ")";
}
// do the same thing for lengths now
// if no length search options given, use 0 to mean any length matches
if (!isset($GLOBALS["Length"]) || empty($GLOBALS["Length"]))
$GLOBALS["Length"] = array();
// make the length list an array if it isn't one
if (!is_array($GLOBALS["Length"]))
$GLOBALS["Length"] = explode(",", $GLOBALS["Length"]);
// if there are any length search options, prepare the sql append
if (sizeof($GLOBALS["Length"]) > 0)
{
$gsql = "SELECT LengthID, SearchGroup FROM length WHERE LengthID IN (" . implode(",", $GLOBALS["Length"]) . ")";
$len_groups = $conn->Execute($gsql);
if ($len_groups === false)
die($conn->ErrorMsg() . " SQL: " . $gsql);
$group_ids = "";
while (!$len_groups->EOF)
{
if (!empty($group_ids))
$group_ids .= ",";
$group_ids .= $len_groups->fields[1];
$len_groups->MoveNext();
}
if (!empty($group_ids))
$sql .= " AND " . $prefix . ".LengthID IN ( " . $group_ids . ")";
}
$urlappend .= "&EquipmentID=" . implode(",", $GLOBALS["EquipmentID"]) .
"&Length=" . implode(",", $GLOBALS["Length"]);
}
function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
$origin_id = Location::GetLocationID($GLOBALS["OriginState"], $GLOBALS["OriginCity"], $GLOBALS["OriginZip"]);
$destination_id = Location::GetLocationID($GLOBALS["DestinationState"], $GLOBALS["DestinationCity"], $GLOBALS["DestinationZip"]);
if (!is_array($origin_id))
{
$o = $origin_id;
$origin_id = array();
$origin_id[0] = $o;
}
if (!is_array($destination_id))
{
$d = $destination_id;
$destination_id = array();
$destination_id[0] = $d;
}
if (!empty($GLOBALS["OriginRadius"]))
{
$origin = new Location($origin_id[0]);
$origin_id = $origin->GetRadiusLocations($GLOBALS["OriginRadius"]);
$urlappend .= "&OriginRadius=" . $GLOBALS["OriginRadius"];
}
if (!empty($GLOBALS["DestinationRadius"]))
{
$destination = new Location($destination_id[0]);
$destination_id = $destination->GetRadiusLocations($GLOBALS["DestinationRadius"]);
$urlappend .= "&DestinationRadius=" . $GLOBALS["DestinationRadius"];
}
// remember search params
if (!empty($GLOBALS["OriginState"]))
$urlappend .= "&OriginState=" . $GLOBALS["OriginState"];
if (!empty($GLOBALS["OriginCity"]))
$urlappend .= "&OriginCity=" . $GLOBALS["OriginCity"];
if (!empty($GLOBALS["OriginZip"]))
$urlappend .= "&OriginZip=" . $GLOBALS["OriginZip"];
if (!empty($GLOBALS["DestinationState"]))
$urlappend .= "&DestinationState=" . $GLOBALS["DestinationState"];
if (!empty($GLOBALS["DestinationCity"]))
$urlappend .= "&DestinationCity=" . $GLOBALS["DestinationCity"];
if (!empty($GLOBALS["DestinationZip"]))
$urlappend .= "&DestinationZip=" . $GLOBALS["DestinationZip"];
// build query
if ($origin_id[0] != -1)
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $origin_id) . ") ";
if ($destination_id[0] != -1)
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $destination_id) . ") ";
}
function GetLocationSearchCriteria1(&$sql, &$urlappend, $prefix)
{
$origin_id = Location::GetMultiLocationID($GLOBALS["OriginState"]);
$destination_id = Location::GetMultiLocationID($GLOBALS["DestinationState"]);
if (!is_array($origin_id))
{
$o = $origin_id;
$origin_id = array();
$origin_id[0] = $o;
}
if (!is_array($destination_id))
{
$d = $destination_id;
$destination_id = array();
$destination_id[0] = $d;
}
if (!empty($GLOBALS["OriginRadius"]))
{
$origin = new Location($origin_id[0]);
$origin_id = $origin->GetRadiusLocations($GLOBALS["OriginRadius"]);
$urlappend .= "&OriginRadius=" . $GLOBALS["OriginRadius"];
}
if (!empty($GLOBALS["DestinationRadius"]))
{
$destination = new Location($destination_id[0]);
$destination_id = $destination->GetRadiusLocations($GLOBALS["DestinationRadius"]);
$urlappend .= "&DestinationRadius=" . $GLOBALS["DestinationRadius"];
}
// remember search params
if (!empty($GLOBALS["OriginState"]))
$urlappend .= "&OriginState=" . $GLOBALS["OriginState"];
if (!empty($GLOBALS["DestinationState"]))
$urlappend .= "&DestinationState=" . $GLOBALS["DestinationState"];
// build query
if ($origin_id[0] != -1)
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $origin_id) . ") ";
if ($destination_id[0] != -1)
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $destination_id) . ") ";
}
function GetMultiLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
$state_vals = array();
$city_vals = array();
$zip_vals = array();
if (!empty($GLOBALS["OriginState"]))
{
$GLOBALS["OriginState"] = explode(",", $GLOBALS["OriginState"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE StateInitials IN ('" . implode("','", $GLOBALS["OriginState"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$state_vals = $vals;
}
if (!empty($GLOBALS["OriginCity"]))
{
$GLOBALS["OriginCity"] = explode(",", $GLOBALS["OriginCity"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE City IN ('" . implode("','", $GLOBALS["OriginCity"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$city_vals = $vals;
}
if (!empty($GLOBALS["OriginZip"]))
{
$GLOBALS["OriginZip"] = explode(",", $GLOBALS["OriginZip"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE ZipCode IN ('" . implode("','", $GLOBALS["OriginZip"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$zip_vals = $vals;
}
// remember search params
if (!empty($state_vals))
$urlappend .= "&OriginState=" . implode(",", $GLOBALS["OriginState"]);
if (!empty($city_vals))
$urlappend .= "&OriginCity=" . implode(",", $GLOBALS["OriginCity"]);
if (!empty($zip_vals))
$urlappend .= "&OriginZip=" . implode(",", $GLOBALS["OriginZip"]);
// build query
$vals = array_unique(array_merge($state_vals, $city_vals, $zip_vals));
if (!empty($vals))
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $vals) . ") ";
if (!empty($GLOBALS["DestinationState"]))
{
$GLOBALS["DestinationState"] = explode(",", $GLOBALS["DestinationState"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE StateInitials IN ('" . implode("','", $GLOBALS["DestinationState"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
{
$sql .= " AND ";
$sql .= $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
}
$urlappend .= "&DestinationState=" . implode(",", $GLOBALS["DestinationState"]);
}
if (!empty($GLOBALS["DestinationCity"]))
{
$GLOBALS["DestinationCity"] = explode(",", $GLOBALS["DestinationCity"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE City IN ('" . implode("','", $GLOBALS["DestinationCity"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
$urlappend .= "&DestinationCity=" . implode(",", $GLOBALS["DestinationCity"]);
}
if (!empty($GLOBALS["DestinationZip"]))
{
$GLOBALS["DestinationZip"] = explode(",", $GLOBALS["DestinationZip"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE ZipCode IN ('" . implode("','", $GLOBALS["DestinationZip"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
$urlappend .= "&DestinationZip=" . implode(",", $GLOBALS["DestinationZip"]);
}
}
}
?>
First off you don't have a class defined named LM_com in the code you have posted.
A proper class is contained in a class structure like that posted below.
class lm_com
{
public function hex2asc($myin)
{
// ...
}
public function get_admin_email()
{
// ...
}
public function GetEquipmentSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetLocationSearchCriteria1(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetMultiLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
}
Secondly you have attempted to call a method in a class using the syntax with a double colon className::methodName.
This syntax when used outside of a class structure only works when calling static class methods. Static class methods do not require creating an instance of the class before calling those methods.
The following format is used for defining a public static method that can be called without creating an instance of the class
public static function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
After you have defined the class and method as I've described then you'll be able to properly make a call to LM_com::GetLocationSearchCriteria($sql, $urlappend, "l");
I want to display a list of all attributes that are added into database but every time I try something it doesn't work. I want to show this inside a div from the from the front page. I tried to insert this into featured.tpl:
<?php
foreach ($attribute_groups as $attribute_group) {
echo $attribute_group['name'];
print_r($attribute_group);
echo '<select name="listaGrupe">';
foreach ($attribute_groups['attribute'] as $attribute) {
echo '<option value="'.$attribute.'">'.$attribute.'</option>';
}
echo '</select>';
}
?>
You ned to use this model
public function getAttributes($data = array()) {
$sql = "SELECT *, (SELECT agd.name FROM " . DB_PREFIX . "attribute_group_description agd WHERE agd.attribute_group_id = a.attribute_group_id AND agd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS attribute_group FROM " . DB_PREFIX . "attribute a LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE ad.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND LCASE(ad.name) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
}
if (!empty($data['filter_attribute_group_id'])) {
$sql .= " AND a.attribute_group_id = '" . $this->db->escape($data['filter_attribute_group_id']) . "'";
}
$sort_data = array(
'ad.name',
'attribute_group',
'a.sort_order'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY attribute_group, ad.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
The in your controller simply load this model and manipulate with the data it returns. By default it returns all the attributes in database
You may be looking for a function format closer to this:
foreach ($attribute_groups as $attribute_group) {
$options = '';
$name = $attribute_group['name'];
$output = '<select name="$name">';
foreach ($attribute_groups['attribute'] as $attribute) {
$options .= '<option value="'.$attribute.'">'.$attribute.'</option>';
}
echo $output.$options.'</select>';
}
check in your controller .. if $attribute_groups have datas in it....
print_r($attribute_groups);
and see.. make sure your $attribute_groups array is not empty... i think u getting that error since your $attribute_groups array is empty...
if incase you are sure, $attribute_groups can be empty then u can check ...
if(!empty($attribute_groups)){
foreach ($attribute_groups as $attribute_group) {
$options = '';
$name = $attribute_group['name'];
$output = '<select name="$name">';
foreach ($attribute_groups['attribute'] as $attribute) {
$options .= '<option value="'.$attribute.'">'.$attribute.'</option>';
}
echo $output.$options.'</select>';
}
}
this will see if your array is empty or not.. if not then foreach()... else do nothing
I am getting error: Invalid argument supplied for foreach()
This is my class for connecting to database:
class dbMySql {
static function Exec($query) {
// open database
$conn = mysql_connect('localhost','root','****');
if($conn == false) {
throw new Exception(mysql_connect_error());
}
mysql_select_db('data',$conn);
$result = mysql_query($query,$conn);
if(is_bool($result) && !$result) {
$error = mysql_error($conn);
mysql_close($conn);
throw new Exception($error);
}
mysql_close($conn);
return $result;
}
}
And I have this code:
echo '{ "results" : [ ';
$gettruck_result = dbMySql::Exec("SELECT id, name, lat, lng FROM data)");
$result_array = array();
foreach($gettruck_result as $row) {
$row_object = '{';
$row_object .= '"id": "' . $row['id'] . '", ';
$row_object .= '"name": "' . $row['name'] . '", ';
$row_object .= '"lat": "' . $row['lat'] . '", ';
$row_object .= '"lng": "' . $row['lng'] . '", ';
$row_object .= '}';
$result_array[] = $row_object;
}
$result_str = implode(", ", $result_array);
echo $result_str;
echo " ] }";
?>
Any idea why am I getting error in foreach loop?
You have to replace:
foreach($gettruck_result as $row) {
... with ...
while($row = mysql_fetch_assoc($gettruck_result)) {
You have checked result array is empty or not..
if(mysql_num_rows($gettruck_result)>0)
{
foreach($gettruck_result as $row) {
.
.
}
}
I'm trying to create an flexible update query. I have now something like this:
$lsQuery = "UPDATE `";
$lsQuery .= $psTableName;
$lsQuery .= " SET ";
foreach($psValues as $lsKey => $lsValue)
{
$lsQuery .= $lsKey;
$lsQuery .= " = '";
$lsQuery .= $lsValue;
$lsQuery .= "' AND ";
}
$lsQuery .= "` ";
$lsQuery .= "WHERE ";
if(isset($psWhere)){
foreach($psWhere as $lsKey => $lsValue)
{
$lsQuery .= $lsKey;
$lsQuery .= " = '";
$lsQuery .= $lsValue;
$lsQuery .= "' AND ";
}
}
$lsQuery = substr($lsQuery,0,(strlen($lsQuery)-5));
But when I print my query on the screen I get something like:
UPDATE persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND WHERE per_email = 'bla#gmail.com'
How can I get rid of this extra 'AND'?
I'd probably start with:
function update($table, $set, $where) {
$change = array();
foreach ($set as $k => $v) {
$change[] = $k . ' = ' . escape($v);
}
$conditions = array();
foreach ($where as $k => $v) {
$conditions[] = $k . ' = ' . escape($v);
}
$query = 'UPDATE ' . $table . ' SET ' .
implode(', ', $change) . ' WHERE ' .
implode(' AND ', $conditions);
mysql_query($query);
if (mysql_error()) {
// deal with it how you wish
}
}
function escape($v) {
if (is_int($v)) {
$v = intval($v);
} else if (is_numeric($v)) {
$v = floatval($v);
} else if (is_null($v) || strtolower($v) == 'null') {
$v = 'null';
} else {
$v = "'" . mysql_real_escape_string($v) . "'";
}
return $v;
}
If you want to keep your existing code.
$lsWhere = array();
foreach($psWhere as $lsKey => $lsValue)
{
$lsWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'";
}
$lsQuery .= join(" AND ", $lsWhere);
It's not a solution I'm particularly proud of, but you can always add $lsQuery .= 'someField=someField'.