i try to get results from my server. my application sending an array with users info and should insert that into the DB.
i get the following result:
{"flag":"failed","msg":"insert event","event id":"89","invitedusers":"[0508690186, 0508690187]","size_invited":1,"user_query":"SELECT id From users WHERE "}
and i would like to know how can i read the values in PHP under "invitedusers":"[0508690186, 0508690187]"
this is my php code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,scheduled,event_status)
VALUES ('$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$output["event id"]=$row["id"];
$json = json_decode($_POST["invitedUsers"]);
$invited_users = str_replace("\\","",$json);
$output["invitedusers"] = $_POST["invitedUsers"] ;
$output["size_invited"] = count($_POST["invitedUsers"]);
$query_users = "SELECT id From users WHERE ";
$i=0;
foreach($invited_users as $user) {
if ($i < (count($invited_users) - 1))
// add a space at end of this string
$query_users .= "users.mobile = '".$user[$i]."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user[$i]."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
/* $event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}*/
}
$output["flag"] = "failed";
}
}
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
i resolve this issue by passing a JSON object from the application and using
json_decode method which convert it back.
Related
Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}
I'm current working on a live leader-board page and i am trying to add a live view counter to it. I am not getting and data sent to the database and its not reading from the database. I have checked the db connection and its working. I have checked the code in php tester and it has no errors.
Take a look and let me know what i missed, Thanks
class VisitorCounterReal {
var $sessionTimeInMin = 5; // time session will live, in minutes
function VisitorCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$this->cleanVisitors();
if ($this->visitorExists($ip))
{
$this->updateVisitor($ip);
} else
{
$this->addVisitor($ip);
}
}
function visitorExists($ip) {
$query = "SELECT * FROM counter WHERE ip = '$ip'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) > 0)
{
return true;
} else
if (mysqli_num_rows($res) == 0)
{
return false;
}
}
function cleanVisitors()
{
$sessionTime = 30;
$query = "SELECT * FROM counter";
$res = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($res))
{
if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)
{
$dsql = "delete from counter where id = $row[id]";
mysqli_query($dsql);
}
}
}
function updateVisitor($ip)
{
$query = "UPDATE counter SET lastvisit = '" . time() . "' WHERE ip =
'$ip'";
mysqli_query($connection, $query);
}
function addVisitor($ip)
{
$query = "INSERT INTO counter(ip, lastvisit) ";
$query .= "VALUES('$ip', '" . time() . "') ";
mysqli_query($connection, $query);
}
function getAmountVisitors()
{
$query = "SELECT COUNT(id) FROM counter";
$res = mysqli_query($connection, $query);
$row = mysqli_fetch_row($res);
return $row[0];
}
function show()
{
echo '<h3>There is ' . $this->getAmountVisitors() . ' watching
online</h3>';
}
}
This is on the live leaderboard page below
<?php
$counter = new VisitorCounterReal; // make a new counter
//content here
$counter->show(); // show the counter
// and here
?>
In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
I am trying to pass a strret address from my application to my PHP server.
when i print the address in the Log.d i got:
העמק 57 גבעת אלה
but the server response is:
$place = $_POST["address"];
$output["addressEditText"] = $place;
and this is what i got from the server:
???? 57 ???? ???
i need that the server will support also hebrew alphabet.
just for notice this response is not from the DB i just copy and past the value of the parameter into the output response.
this is my page code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
include 'gcm.php';
require_once 'DBFunctions.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$dbF = new DBFunctions($dblink);
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$date." ".$_POST["s_time"];
$e_time = $date." ".$_POST["e_time"];
$s_time =date("Y-m-d H:i:s",strtotime($s_time));
$e_time = date("Y-m-d H:i:s",strtotime($e_time));
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$mng_name = $_POST["manager_name"];
$place = $_POST["address"];
$output["addressEditText"] = $place;
$mode = $_POST["mode"];
if($sched == "true"){
$exp_val = "";
$type = "";
$repeat = $_POST["repeat"];
$duration = $_POST["duration"];
$expiration_tag = $_POST["sched_tag"];
switch($expiration_tag){
case "unlimited":{
$exp_val = "unlimited";
$type = $exp_val;
break;
}
case "Year":{
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
case "events_number":
$exp_val = $_POST["value"];
$type = "counter";
break;
case "by_date":
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
$output["repeat"] = $repeat;
$output["duration"] = $duration;
$output["exp_val"] = $exp_val;
$output["type"] = $type;
}
if($mode == "edit"){
$event_id = $_POST["event_id"];
$invited_users_size = 0;
if(isset($_POST["invitedUsers"])){
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$invited_users_size = count($json_uesr_ids);
}
if(isset($_POST["invitedUsers"])){
$result_q = $dbF -> DeleteEventFromAttending($event_id);
if(!$result_q)
{
$output["flag"]= "delete failed";
$output["msg"] = $result_q;
return json_encode($output);
}else {
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$output["json_users"] = $json_uesr_ids;
$get_users_reg_ids = $dbF->getUserSByIds($json_uesr_ids, count($json_uesr_ids));
$reg_ids = array();
$i = 0;
while ($row_user = mysqli_fetch_assoc($get_users_reg_ids)) {
$reg_ids[$i] = $row_user["gcm_id"];
$i++;
}
$output["ids"] = $reg_ids;
$output["size"] = count($json_uesr_ids);
$result_q = $dbF->InsertIntoAttendingUpdatedUsers($json_uesr_ids, $event_id, count($json_uesr_ids),"awaiting reply");
$output["insert_res"] = $result_q;
if (!$result_q) {
$output["flag"] = "update_insert failed";
$output["msg"] = $result_q;
return json_encode($output);
} else {
$output["flag"] = "update_success";
$output["msg"] = $result_q;
}
//send notification on update to users
$gcm = new GCM();
$data = array();
$message = "The event " . $sport . " in " . $place . " in " . $date . " updated,Please click on Join in order to confirm registration.";
$data['message'] = $message;
$data['date'] = $date;
$data['private'] = $event_type;
$data['start_time'] = date("H:i", strtotime($s_time));
$data['end_time'] = date("H:i", strtotime($e_time));
$data['inviter'] = $mng_name;
$data['event_id'] = $event_id;
$data['location'] = $place;
$gcm_res = $gcm->send_notification($reg_ids, $data);
$output["gcm_res"] = $gcm_res;
//send notification on update to users
}
}
$result_q = $dbF ->checkIfEventIsExistBeforeUpdate($lon,$lat,$date,$s_time,$e_time,$event_id);
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else {
$no_of_rows_check_event = mysqli_num_rows($result_q);
if ($no_of_rows_check_event > 0) {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$result_q = $dbF -> UpdateEvent($event_id,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,'1',$invited_users_size,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
$output["res"] = $result_q;
$output["sched"] = $sched;
if($sched == "true")
{
$output["sched_res"] = "true";
}
else{
$output["sched_res"] = "false";
}
$affected_row = mysqli_affected_rows($dblink);
if(!$result_q)
{
$output["flag"]= "update_failed";
$output["query_res"] = $result_q;
$output["msg"] = "failed to update event";
$output["affected row"] = $affected_row;
}
else{
$output["flag"]= "update_success";
$output["query_res"] = $result_q;
$output["msg"] = "success to update event";
$output["affected row"] = $affected_row;
}
}
}
}
else{
$result_q = $dbF ->checkIfEventIsExist($lon,$lat,$date,$s_time,$e_time);
$output["query"] = $result_q;
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else{
$no_of_rows_check_event = mysqli_num_rows($result_q);
$output["no_of_rows"] = $no_of_rows_check_event;
if($no_of_rows_check_event > 0)
{
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$output["flag"] = "success";
$output["msg"] = "insert event";
$num_of_invited_users = 0;
if(isset($_POST["jsoninvited"])){
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$num_of_invited_users = (count($json));
$output["size_invited"] = count($json);
}
$result = $dbF -> InsertNewEvent($manager,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,$num_of_invited_users,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["jsoninvited"])){
$event_s_res = $dbF ->getEventIdByDateAndTime($date,$s_time,$e_time);
$output["my_squery"] =$event_s_res;
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["event_id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$size_of_param = (count($json));
$event_user_s_res = $dbF -> getUserIdAndRegId($json,$size_of_param);
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$result = $dbF->insertIntoAttendingTable($event_user_s_res, $event_id, $size_of_param);
$insert_query_res = $result["res"];
$output["query"] = $result["query"];
$registration_ids = $result["reg_ids"];
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}
else{
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$data = array();
$message = "Would like to invite you to play ".$sport.", Please click on Join in order to add you into the event.";
$data['message'] = $message;
$data['date'] = $date;
$data['start_time'] = date("H:i",strtotime($s_time));
$data['end_time'] = date("H:i",strtotime($e_time));
$data['inviter'] = $mng_name;
$data['private'] = $event_type;
$data['event_id'] = $event_id;
$data['location'] = $place;
$output["gcm_message"]=$data;
$gcm_res = $gcm->send_notification($registration_ids,$data);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
}
}
}//get inside creating event mode.
return json_encode($output);
}
}
this is my client side:
public void sendDataToDBController() {
BasicNameValuePair mode_req;
LatLng lonlat = locationTool.getLocationFromAddress(addressEditText.getText().toString());
if(lonlat == null)
{
Log.d("location is:","location not found");
sv.scrollTo(0, 0);
addressEditText.setError("Location was not found!");
return;
}
Log.d("found location",lonlat.latitude+""+lonlat.longitude);
BasicNameValuePair tagreq = new BasicNameValuePair(Constants.TAG_REQUEST,"create_event");
Log.d("event mode",mode);
if(mode.equals(Constants.MODE_CREATE))
{
Log.d("event mode","create");
mode_req = new BasicNameValuePair(Constants.TAG_MODE,Constants.MODE_CREATE);
}
else {
Log.d("event mode","update");
mode_req = new BasicNameValuePair(Constants.TAG_MODE, Constants.MODE_UPDATE);
}
Log.d("addressEditText",addressEditText.getText().toString());
BasicNameValuePair address = new BasicNameValuePair("address",addressEditText.getText().toString());
BasicNameValuePair sport = new BasicNameValuePair("sport_type",sportSpinner.getSelectedItem().toString());
Log.d("sport_type",sportSpinner.getSelectedItem().toString());
BasicNameValuePair date = new BasicNameValuePair("date",btnStartdate.getText().toString());
BasicNameValuePair startTime = new BasicNameValuePair("s_time",btnstartTime.getText().toString());
BasicNameValuePair endTime = new BasicNameValuePair("e_time",btnendTime.getText().toString());
BasicNameValuePair longtitude = new BasicNameValuePair(Constants.TAG_LONG,String.valueOf(lonlat.longitude));
BasicNameValuePair latitude = new BasicNameValuePair(Constants.TAG_LAT,String.valueOf(lonlat.latitude));
BasicNameValuePair event_type = new BasicNameValuePair("event_type",String.valueOf(privateEventCbox.isChecked()));
BasicNameValuePair gender = new BasicNameValuePair(Constants.TAG_GEN,String.valueOf(genderSpinner.getSelectedItem().toString()));
BasicNameValuePair min_age = new BasicNameValuePair("minAge",String.valueOf(minAgeEditText.getText()));
BasicNameValuePair participants = new BasicNameValuePair("max_participants",maxParticipantsEdittext.getText().toString());
BasicNameValuePair scheduled = new BasicNameValuePair("scheduled",String.valueOf(reccuringEventCbox.isChecked()));
BasicNameValuePair mob_manager = new BasicNameValuePair("manager",sm.getUserDetails().get(Constants.TAG_USERID));
BasicNameValuePair manager_name = new BasicNameValuePair("manager_name",sm.getUserDetails().get(Constants.TAG_NAME));
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
if(mode.equals(Constants.MODE_UPDATE)){
BasicNameValuePair eventId = new BasicNameValuePair("event_id",event_id);
nameValuePairList.add(eventId);
}
if(invitedUsers != null)
{
if(invitedUsers.size() > 0)
{
String[] users = new String[invitedUsers.size()];
JSONArray invited = new JSONArray();
for(int i=0 ; i < invitedUsers.size(); i++)
{
if(mode.equals(Constants.MODE_CREATE))
users[i]= invitedUsers.get(i).getMobile();
else
users[i]= invitedUsers.get(i).getId();
invited.put(users[i]);
}
String json = invited.toString();
Log.d("string array", Arrays.toString(users));
BasicNameValuePair invitedusers = new BasicNameValuePair("invitedUsers",Arrays.toString(users));
BasicNameValuePair jsonInvited = new BasicNameValuePair("jsoninvited",json);
nameValuePairList.add(invitedusers);
nameValuePairList.add(jsonInvited);
}
}
if(sched_res != null && reccuringEventCbox.isChecked() == true){
String repeatval ="";
String duration ="";
String tag = "";
String val = "";
BasicNameValuePair sched_val = null;
try {
repeatval = sched_res.getString("repeat");
duration = sched_res.getString("duration");
JSONArray jsonarr = new JSONArray(sched_res.getString("radio_group"));
tag = jsonarr.getJSONObject(0).getString(Constants.TAG_REQUEST);
sched_val = new BasicNameValuePair("value",jsonarr.getJSONObject(0).getString("val"));
} catch (JSONException e) {
e.printStackTrace();
}
BasicNameValuePair sched_repeat = new BasicNameValuePair("repeat",repeatval);
BasicNameValuePair sched_duration = new BasicNameValuePair("duration",duration);
BasicNameValuePair sched_tag = new BasicNameValuePair("sched_tag",tag);
nameValuePairList.add(sched_repeat);
nameValuePairList.add(sched_duration);
nameValuePairList.add(sched_tag);
if(sched_val != null)
nameValuePairList.add(sched_val);
}
nameValuePairList.add(manager_name);
nameValuePairList.add(mob_manager);
nameValuePairList.add(tagreq);
nameValuePairList.add(mode_req);
nameValuePairList.add(sport);
nameValuePairList.add(date);
nameValuePairList.add(address);
nameValuePairList.add(startTime);
nameValuePairList.add(endTime);
nameValuePairList.add(min_age);
nameValuePairList.add(longtitude);
nameValuePairList.add(latitude);
nameValuePairList.add(event_type);
nameValuePairList.add(participants);
nameValuePairList.add(scheduled);
nameValuePairList.add(gender);
dbController = new DBcontroller(getActivity().getApplicationContext(),this);
dbController.execute(nameValuePairList);
}
after searching for a while i solved this issue by:
add this code in my server side:
if(!mysqli_set_charset($dblink, 'utf8')) {
echo 'the connection is not in utf8';
exit();
}
I have inherited the below code, which creates a web interface for a MySQL database named 'database_name' and defined by the variable $database.
I want to add an additional database to this script, so that the same interface can be created this second database (which is set up in exactly the same way as the first database with the same tables names, etc., but contains different data). Is there a way to make $database a string array which I can loop over for multiple database names?
<?php
class DatabaseInterface {
public $host = "localhost"; //(name or ip address)
public $userName = "aksfhah";
public $passWord = "**********";
public $database = 'database_name';
public $tableData = "measurements";
public $tableMinbins = "minbins";
public $tableHourbins = "hourbins";
public $tableDaybins = "daybins";
public $tableDescriptions = "measurementDescriptions";
public $tableSpecs = "experimentDescriptions";
public $connection;
public function __construct($databaseName = "database_name") {
$this->database = $databaseName;
$this->connect();
}
public function connect($databaseName = null) {
$dbh = mysql_connect($this->host, $this->userName, $this->passWord);
if (is_null($databaseName)) {
mysql_select_db($this->database);
} else {
mysql_select_db($databaseName);
}
$this->connection = $dbh;
return $dbh;
}
public function initializeDatabase() {
$this->createDataTable($this->tableData);
$query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255),
description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
private function createDataTable($tableName) {
$query = "CREATE TABLE IF NOT EXISTS $tableName (
id smallint(5) unsigned NOT NULL,
time datetime NOT NULL,
measurement float DEFAULT NULL,
rebinned tinyint(4) DEFAULT '0',
PRIMARY KEY (id,time),
KEY (rebinned,id)
) ENGINE=MyISAM";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertById($time, $value, $sensorID);
}
public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) {
if(is_null($tableName)){
$tableName= $this->tableData;
}
if (count($timeArray) == 0)
return 0;
$query = "insert ignore into $tableName (id,time,measurement)
VALUES ";
for ($index = 0; $index < count($timeArray); $index++) {
$timeString = $timeArray[$index]->format("Y-m-d H:i:s");
$value = $valueArray[$index];
$query = $query . "('$sensorID','$timeString','$value'),";
}
$query = substr($query, 0, strlen($query) - 1); //trim final comma
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else
return mysql_affected_rows();
}
public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName);
}
public function insertById(DateTime $time, $value, $sensorID) {
$timeString = $time->format("Y-m-d H:i:s");
$query = "insert ignore into $this->tableData (id,time,measurement)
VALUES ('$sensorID','$timeString','$value')";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else if (mysql_affected_rows() == 0) {
return false;
} else {
return true;
}
}
public function createIdFromDescription($channelDescription, $experimentDescription, $type) {
$sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription);
if (!$sensorId) {
$query = "insert ignore into $this->tableDescriptions (description,experimentname,type)
VALUES ('$channelDescription','$experimentDescription','$type')";
$result = mysql_query($query);
$sensorId = mysql_insert_id();
}
return $sensorId;
}
public function getIdFromDescription($measurementDescription, $experimentDescription) {
$sensorId = false;
$query = "select id from $this->tableDescriptions where description like '$measurementDescription'
&& experimentname like '$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$sensorId = $row['id'];
}
return $sensorId;
}
function getDataById($id, $startDate, $endDate, $interval = "") {
$data = array();
$startDateString = $startDate->format("Y-m-d H:i:s");
$endDateString = $endDate->format("Y-m-d H:i:s");
$query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
//$time = new DateTime($row['time']);
$data[] = array($row['time'], $row['measurement'] * 1);
}
return $data;
}
public function getMostRecentData($id, $table) {
$query = "select date(max(time)) as time,measurement from $table where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
} elseif (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
return $row;
} else {
return false;
}
}
public function getExperimentList() {
$list = array();
$query = "select distinct experimentname from $this->tableDescriptions";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[] = $row['experimentname'];
}
return $list;
}
public function getChannelList($experimentDescription) {
$list = array();
$query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[$row['description']] = array("id" => $row['id'], "type" => $row['type']);
}
return $list;
}
public function getDescriptionFromId($id) {
$query = "select * from $this->tableDescriptions where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_fields($result) > 0) {
$row = mysql_fetch_array($result);
return array($row['type'], $row['description'], $row['experimentname']);
} else {
return false;
}
}
public function getDisplayName($experimentName) {
$query = "select displayName from $this->tableSpecs where experimentName='$experimentName'";
$result = mysql_query($query);
echo mysql_error();
$row = mysql_fetch_array($result);
if ($row) {
return $row['displayName'];
} else {
return false;
}
}
public function simpleQuery($query) {
$result = mysql_query($query);
echo mysql_error();
if ($result) {
$row = mysql_fetch_array($result);
if ($row) {
return $row[0];
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) {
$this->createDataTable($tableTarget);
echo "Updating $tableSource to set rebinned from 0 to 2...";
$query = "update $tableSource set rebinned=2 where rebinned =0;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
$numRows = mysql_affected_rows();
echo "Found $numRows records in $tableSource that need rebinning...\n";
$query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;";
$result = mysql_query($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$mintime = $row['mintime'];
echo $id . "...";
$query = "INSERT INTO $tableTarget (id,time,measurement,rebinned)
SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0
FROM $tableSource WHERE id=$id && time>='$mintime'
GROUP BY id,floor(unix_timestamp(time)/$numSeconds)
ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;";
mysql_query($query);
//echo $query;
echo mysql_error();
echo "Done.\n";
}
echo "Updating $tableSource to set rebinned from 2 to 1...";
$query = "update $tableSource set rebinned=1 where rebinned =2;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
}
}
public function getDCPower($experimentName, $startDate, $endDate) {
$out = array();
$query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins);
if ($query) {
if ($startDate != "") {
$query = $query . " && m0.time>='$startDate' ";
}
if ($endDate != "") {
$query = $query . " && m0.time<='$endDate' ";
}
echo $query;
$result = mysql_query($query);
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
// echo $row['time'].", ".$row['power']."\n";
$out[] = array($row['time'], $row['power'] + 0);
}
return $out;
} else {
return FALSE;
}
}
}
?>
Is there a way to make $database a string array which I can loop over for multiple database names?
No, it does not work that way. The script you have defines a class. You have to look in the file that uses that class, where there will be something like
$interface = new DatabaseInterface("database1");
There you'll be able to do things such as
$interface = array();
$interface[0] = new DatabaseInterface("database1");
$interface[1] = new DatabaseInterface("database2");
and use two instances of the interface against the two databases.