receiving newline inside a json object - php

i am trying to bring a set of texts from a PostgreSQL database (field type is text) with ajax into my webpage. The problem i encouter is the newline, it works great when there is no newlines into the text in database, but when i use new lines in the text inside database, the json doesnt give me the data it stored.
function selectCalendarEvents(user_id, event_datestart, event_datestop, callback) {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText.substr(0, 6) == "error ")
alert(errorName[request.responseText.substr(6)]);
else {
jsonCalendarEvents = $.parseJSON(request.responseText);
selectEvents(user_id, event_datestart, event_datestop, callback);
}
}
}
request.open("GET", "php/calendar.php?action=selectCalendarEvents&user_id=" + user_id + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop, true);
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
request.send();
}
this is my javascript function which requests the data set
if($action == "selectCalendarEvents") {
$user_id = $_GET["user_id"];
$event_datestart = "'" . $_GET["event_datestart"] . "'";
$event_datestop = "'" . $_GET["event_datestop"] . "'";
require_once("connect.php");
$query = "SELECT event_id, event_name, event_datestart, event_datestop, event_timestart, event_timestop, calendar_events.calendar_group, calendar_color, event_info FROM calendar_events LEFT JOIN calendar_calendars ON calendar_events.calendar_group = calendar_calendars.calendar_group WHERE user_id = " . $user_id . " AND calendar_show = true AND event_datestart <= ". $event_datestop . " AND event_datestop >= " . $event_datestart;
$result = pg_query($connect, $query);
if(!$result)
die("error 1"); // query error
$comma = '';
$json = '{"events":[';
while ($row = pg_fetch_row($result)) {
$json .= $comma . '{';
$json .= '"event_id":"' . $row[0] . '",';
$json .= '"event_name":"' . $row[1] . '",';
$json .= '"event_datestart":"' . $row[2] . '",';
$json .= '"event_datestop":"' . $row[3] . '",';
$json .= '"event_timestart":"' . $row[4] . '",';
$json .= '"event_timestop":"' . $row[5] . '",';
$json .= '"calendar_group":"' . $row[6] . '",';
$json .= '"calendar_color":"' . $row[7] . '",';
$json .= '"event_info":"' . $row[8] . '"';
$json .= '}';
$comma = ',';
}
$json .= ']}';
echo $json;
}
this is my php which returns the dataset. If row[8] aka event_info stores text with newlines in it .. when i try to populate my calendar with the events, it seems the json doesnt store any data in it or smt like that.

I found out that i should replace \r\n with <br/> and it will work. im using like this replace(/\r\n/g, "<br/>") when i give the response string to json
jsonCalendarEvents = $.parseJSON(request.responseText.replace(/\r\n/g, "<br/>"));

Related

php database query (phpMyAdmin) only brings back one value (the first one) into amcharts

The below php database query (from phpMyAdmin) only brings back one value (the first one or the oldest) into amcharts:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
mysql_connect("hostname", "username", "password");
mysql_select_db("database name");
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = mysql_query($query) OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
return $content;
// Variable now on 2
$zeilenzaehler = 2;
}
}
}
?>
Everything else looks like its working fine. Many thanks for the help
You return the first found result in your while-loop. That is why you have just one result. Also as mysql_* functions are depreceted consider switching to
mysqli_* or PDO.
I am adding code from your request:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
$mysqli = new mysqli("hostname", "username", "password", "database name");
if ($mysqli->connect_error) {
// your error handling here
}
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = $mysqli->query($query);
if (FALSE === $result) {
// you can put different error handling here
echo 'Error: ' . $query . ' ' . $mysql->error);
die();
}
$total = array();
while (NULL !== ($row = $result->fetch_array()))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// return $content;
// if you not return the first result you can gather results in array, so array will contain every row in result, $total[0], $total[1]...:
// $total[] = $content; or:
$total[] = "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// Variable now on 2
$zeilenzaehler = 2;
}
$result->free();
return $total; // return all rows
}
}
?>

Error Trying To Call PHP Class

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");

MySQL query through PHP fix

I'm making a page, where depending on the HTML form data gets inserted/updated/deleted into/from the database.
As far as for the UPDATE goes, I have no more ideas how to fix it. The thing is, that you can update anything you want (for example nazwa_klubu only, if let's say you've changed your old nazwa_klubu and want to keep the new name (nazwa klubu = club name) in the database you type the name that you want to change to into Nazwa klubu in the Wprowadz zmiany form, and then in the second Nazwa klubu you type the name you want to be changed.
I believe it is a minor upgrade to make it all work, without having to put countless if cases, but it's my third day with PHP, so I'm confused.
EDIT: So basically, this function works properly, if all fields are filled. But I want it to work even if we fill some of fields - well, I hope you get my point. What's the point of UPDATE if you can't even use it correctly? Rhetorical Q.
And this is how it currently works:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName', WHERE nazwa_klubu = 'OldClubName' AND
But obviously I want this to work like this:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName' WHERE nazwa_klubu = 'OldClubName'
No matter how many input's I'll fill in this form. The first 5 inputs are responsible for SET side, and the second five are after WHERE clause.
Here's the code of the function
function update($table, $data)
{
$new_klub = 'nazwa_klubu = ' . '\'' . $data[data1] . '\',';
$new_adres = 'adres_klubu = ' . '\'' . $data[data2] . '\',';
$new_zespol = 'nazwa_zespolu = ' . '\'' . $data[data3] . '\',';
$new_ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data4] . '\',';
$new_wystep = 'data_wystepu = ' . '\'' . $data[data5] . '\',';
$klub = 'nazwa_klubu = ' . '\'' . $data[data6] . '\' AND';
$adres = 'adres_klubu = ' . '\'' . $data[data7] . '\' AND';
$zespol = 'nazwa_zespolu = ' . '\'' . $data[data8] . '\' AND';
$ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data9] . '\' AND';
$wystep = 'data_wystepu = ' . '\'' . $data[data10] . '\'';
if (empty($data[data1]) AND empty($data[data2]) AND
empty($data[data3]) AND empty($data[data4]) AND empty($data[data5])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac jakie zmiany chcesz wprowadzic</span>';
exit;
}
if (empty($data[data6]) AND empty($data[data7]) AND
empty($data[data8]) AND empty($data[data9]) AND empty($data[data10])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac na czym chcesz dokonac zmian</span>';
exit;
}
if (empty($data[data1])) {
$new_klub = '';
}
if (empty($data[data2])) {
$new_adres = '';
}
if (empty($data[data3])) {
$new_zespol = '';
}
if (empty($data[data4])) {
$new_ile = '';
}
if (empty($data[data5])) {
$new_wystep = '';
}
if (empty($data[data6])) {
$klub = '';
}
if (empty($data[data7])) {
$adres = '';
}
if (empty($data[data8])) {
$zespol = '';
}
if (empty($data[data9])) {
$ile = '';
}
if (empty($data[data10])) {
$wystep = '';
}
$safe_updates = "SET SQL_SAFE_UPDATES = 0";
$sql = "UPDATE $table SET
$new_klub
$new_adres
$new_zespol
$new_ile
$new_wystep
WHERE
$klub
$adres
$zespol
$ile
$wystep
";
echo $new_klub;
mysql_query($safe_updates);
$result = mysql_query($sql);
if (!$result) {
echo '<span class="error">' . mysql_error() . '</span><br>' . $sql . '';
}
else {
echo '<span class="success">Wprowadzono zmiany' . $sql . '</span><br>';
}
}
You shouldn't use stack overflow as somewhere ask questions like "Fix my code".
But, you could just put all your $new_ variables into an array
$new = array(
'klub' => 'nazwa_klubu = ' . '\'' . $data[data1] . '\',',
'adres' => 'adres_klubu = ' . '\'' . $data[data2] . '\',',
);
And then you can implode your array
$sql = implode(', ', $new);
Then you wont get trailing commas. Then use the same logic with AND and you'll get your SQL looking okay.

JSON formatting errors for two files

I would like to know, I have just created my datatables, but two of them are giving JSON formatting errors. I am doing a join of two tables in these two. I tried running the query in phpmyadmin, and it works just fine Here is one example of my server-side files:
<?php
$username="drup197";
$password="*****";
$database="census";
$server="localhost";
$link = mysqli_connect($server,$username,$password,$database);
//#mysql_select_db($database,$link) or die( "Unable to select database");
$query = "
SELECT *
FROM national_age_gender_demographics INNER JOIN arizona_age_gender_demogrpahics
WHERE national_age_gender_demographics.age_group = arizona_age_gender_demogrpahics.age_group
ORDER BY national_age_gender_demographics.index_number";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
//print_r($row);
$tableData = '{"aaData": [[';
$numRows = $result->num_rows;
$row = mysqli_fetch_array($result);
for ($i = 0; $i < $numRows; $i++) {
if ($i != 0) {
$tableData .= ",[";
}
$tableData .= '"' . $row['age_group'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.both_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.male_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.female_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.male_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.female_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.both_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.males_per_100_females'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.both_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.male_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.female_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.male_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.female_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.both_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.males_per_100_females'] . '"]';
if ($i != $numRows - 1) {
$row = mysqli_fetch_array($result);
}
}
$tableData .= ']}';
echo $tableData;
?>
Does anyone know what is wrong here?
Firstly Steven is right, its better to use the json encode (or at least neater) to create your json, save you from the messy ifs and bracket business.
I would also recommend using mysqli_fetch_assoc rather than using mysqli_fetch_array, which as you currently specified should return both associative and numbered results (see here http://php.net/manual/en/mysqli-result.fetch-array.php), which probably messes up your results.
eg:
...
$row = mysqli_fetch_assoc($result);
$json_data = json_encode($row);
echo $json_data;
?>
Try that and see how you get on?

How to got trough the mysql results in php

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) {
.
.
}
}

Categories