Hi In the below code data not saving into database.In the file I am working with android.client side data coming correctly. from client side I am passing username,password,groupname,friendusername it will return array list.
Why I am not getting where i did mistake.
php
case "CreateGroup":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
if (isset($_REQUEST['friendUserName']))
{
$friendUserName = $_REQUEST['friendUserName'];
$groupname = $_REQUEST['groupname'];
$sql = "select Id from users where username='".$friendUserName."' limit 1";
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$requestId = $row->Id;
$groupname = $row->Id;
if ($row->Id != $userId)
{
$sql = "insert into group(providerId, requestId, groupname)
values(".$userId.", ".$requestId.", ".$groupname.")";
echo $sql;
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
Try this..
$sql = "insert into group(providerId, requestId, groupname)values(".$userId.", ".$requestId.", ".$groupname.")";
to
$sql = mysql_query("insert into group(providerId, requestId, groupname)values('$userId','$requestId','$groupname')");
if ($sql)
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
Related
Hi in the below code I am getting the invalid json output.How to get the correct json response.[{"groupname":"New"},{"groupname":"Group"}] this output only expecting but it coming one more time
where I did mistake I am not getting
[{"groupname":"New"}][{"groupname":"New"},{"groupname":"Group"}]
Expected output is this one:
[{"groupname":"New"},{"groupname":"Group"}]
php
case "DispalyGroupDetails":
$userId = authenticateUser($db, $username, $password);
$array = array();
if ($userId != NULL)
{
if (isset($_REQUEST['username']))
{
$username = $_REQUEST['username'];
$sql = "select Id from users where username='$username' limit 1";
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$sql = "SELECT g.groupname
FROM `users` u, `friends` f, `group` g
WHERE u.Id=f.providerId and f.providerId=g.providerId
GROUP BY g.id, g.groupname";
$theResult = $db->query($sql);
while( $theRow = $db->fetchObject($theResult))
{
$json_output[]=$theRow;
print(json_encode($json_output));
}
//$out = SUCCESSFUL;
}
else
{
//$out = FAILED;
}
}
else
{
//$out = FAILED;
}
}
else
{
//$out = FAILED;
}
}
else
{
//$out = FAILED;
}
break;
put this line after while loop
print(json_encode($json_output));
Hi in the below I am printing the group name using echo function.But I want to return the echo message in the form of array.Because these echo message I am reading in client side.
for example my output coming like this:
NewGroup-->New is one groupname and Group is the second groupname
Excepted output:
{New},{Group}
php
case "DispalyGroupDetails" :
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL) {
if (isset($_REQUEST['username'])) {
$username = $_REQUEST['username'];
$sql = "select Id from users where username='$username' limit 1";
if ($result = $db -> query($sql)) {
if ($row = $db -> fetchObject($result)) {
$sql = "SELECT g.id,g.groupname
FROM `users` u, `friends` f, `group` g
WHERE u.Id=f.providerId and
f.providerId=g.providerId
GROUP BY g.id, g.groupname";
$theResult = $db -> query($sql);
if ($theResult) {
while ($theRow = $db -> fetchObject($theResult)) {
echo $theRow -> groupname;
}
$out = SUCCESSFUL;
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
break;
Add the group name into an array, then json_encode($array);.
NOTE: this code is not tested as I do not have your database.
like this:
$userId = authenticateUser($db, $username, $password);
$array = array();
if ($userId != NULL) {
if (isset($_REQUEST['username'])) {
$username = $_REQUEST['username'];
$sql = "select Id from users where username='$username' limit 1";
if ($result = $db->query($sql)) {
if ($row = $db->fetchObject($result)) {
$sql = "SELECT g.id,g.groupname FROM `users` u, `friends` f, `group` g WHERE u.Id=f.providerId and f.providerId=g.providerId GROUP BY g.id, g.groupname";
$theResult = $db->query($sql);
if ($theResult) {
$count = 0;
while( $theRow = $db->fetchObject($theResult)) {
$array[$count] = $theRow->groupname;
$count++;
}
$out = SUCCESSFUL;
echo json_encode($array);
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
} else {
$out = FAILED;
}
}
else {
$out = FAILED;
}
Hi in the below it's returns the SUCCESSFUL message but I am not getting the id,groupnames.
How to execute the select query in the below code.I wan the record details of id and groupname.
Can any one help me
php
case "DispalyGroupDetails":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
if (isset($_REQUEST['username']))
{
$username = $_REQUEST['username'];
$sql = "select Id from users where username='$username' limit 1";
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$sql = "select g.id,g.groupname from `users` u, `friends` f,`group` g
where u.Id=f.providerId and f.providerId=g.providerId";
echo $sql;
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
Try something like this. You need to fetch the contents of the query as opposed to just getting whether the query was successful.
$sql = "select g.id,g.groupname from `users` u, `friends` f,`group` g
where u.Id=f.providerId and f.providerId=g.providerId";
echo $sql;
$theResult = $db->query($sql);
if ($theResult) {
$theRow = $db->fetchObject($theResult);
echo $theRow->id;
echo $theRow->groupname;
//Etc
$out = SUCCESSFUL;
} else {
$out = FAILED;
}
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.
i have 2 server codes written in php that I want to merge.
the first code is to work with the mysql database and fire queries at the database and give back results
<?php
//TODO: show error off
require_once("mysql.class.php");
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project";
$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName);
// if operation is failed by unknown reason
define("FAILED", 0);
define("SUCCESSFUL", 1);
// when signing up, if username is already taken, return this error
define("SIGN_UP_USERNAME_CRASHED", 2);
// when add new friend request, if friend is not found, return this error
define("ADD_NEW_USERNAME_NOT_FOUND", 2);
// TIME_INTERVAL_FOR_USER_STATUS: if last authentication time of user is older
// than NOW - TIME_INTERVAL_FOR_USER_STATUS, then user is considered offline
define("TIME_INTERVAL_FOR_USER_STATUS", 60);
define("USER_APPROVED", 1);
define("USER_UNAPPROVED", 0);
$username = (isset($_REQUEST['username']) && count($_REQUEST['username']) > 0)
? $_REQUEST['username']
: NULL;
$password = isset($_REQUEST['password']) ? md5($_REQUEST['password']) : NULL;
$port = isset($_REQUEST['port']) ? $_REQUEST['port'] : NULL;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : NULL;
if ($username == NULL || $password == NULL)
{
echo FAILED;
exit;
}
$out = NULL;
error_log($action."\r\n", 3, "error.log");
switch($action)
{
case "authenticateUser":
// code for generating list of shares.
if ($port != NULL
&& ($userId = authenticateUser($db, $username, $password, $port)) != NULL)
{
// providerId and requestId is Id of a friend pair,
// providerId is the Id of making first friend request
// requestId is the Id of the friend approved the friend request made by providerId
// fetching friends,
// left join expression is a bit different,
// it is required to fetch the friend, not the users itself
$sql = "select u.Id, u.username, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP,
f.providerId, f.requestId, f.status, u.port
from friends f
left join users u on
u.Id = if ( f.providerId = ".$userId.", f.requestId, f.providerId )
where (f.providerId = ".$userId." and f.status=".USER_APPROVED.") or
f.requestId = ".$userId." ";
if ($result = $db->query($sql))
{
$out .= "<data>";
$out .= "<user userKey='".$userId."' />";
while ($row = $db->fetchObject($result))
{
$status = "offline";
if (((int)$row->status) == USER_UNAPPROVED)
{
$status = "unApproved";
}
else if (((int)$row->authenticateTimeDifference) < TIME_INTERVAL_FOR_USER_STATUS)
{
$status = "online";
}
$out .= "<friend username = '".$row->username."' status='".$status."' IP='".$row->IP."'
userKey = '".$row->Id."' port='".$row->port."'/>";
// to increase security, we need to change userKey periodically and pay more attention
// receiving message and sending message
}
$out .= "</data>";
}
else
{
$out = FAILED;
}
}
else
{
// exit application if not authenticated user
$out = FAILED;
}
break;
case "signUpUser":
if (isset($_REQUEST['email']))
{
$email = $_REQUEST['email'];
$sql = "select Id from users
where username = '".$username."' limit 1";
if ($result = $db->query($sql))
{
if ($db->numRows($result) == 0)
{
$sql = "insert into users(username, password, email)
values ('".$username."', '".$password."', '".$email."') ";
error_log("$sql", 3 , "error_log");
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else {
$out = FAILED;
}
}
else
{
$out = SIGN_UP_USERNAME_CRASHED;
}
}
}
else
{
$out = FAILED;
}
break;
case "addNewFriend":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
if (isset($_REQUEST['friendUserName']))
{
$friendUserName = $_REQUEST['friendUserName'];
$sql = "select Id from users
where username='".$friendUserName."'
limit 1";
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$requestId = $row->Id;
if ($row->Id != $userId)
{
$sql = "insert into friends(providerId, requestId, status)
values(".$userId.", ".$requestId.", ".USER_UNAPPROVED.")";
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED; // user add itself as a friend
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
case "responseOfFriendReqs":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
$sqlApprove = NULL;
$sqlDiscard = NULL;
if (isset($_REQUEST['approvedFriends']))
{
$friendNames = split(",", $_REQUEST['approvedFriends']);
$friendCount = count($friendNames);
$friendNamesQueryPart = NULL;
for ($i = 0; $i < $friendCount; $i++)
{
if (strlen($friendNames[$i]) > 0)
{
if ($i > 0 )
{
$friendNamesQueryPart .= ",";
}
$friendNamesQueryPart .= "'".$friendNames[$i]."'";
}
}
if ($friendNamesQueryPart != NULL)
{
$sqlApprove = "update friends set status = ".USER_APPROVED."
where requestId = ".$userId." and
providerId in (select Id from users where username in (".$friendNamesQueryPart."));
";
}
}
if (isset($_REQUEST['discardedFriends']))
{
$friendNames = split(",", $_REQUEST['discardedFriends']);
$friendCount = count($friendNames);
$friendNamesQueryPart = NULL;
for ($i = 0; $i < $friendCount; $i++)
{
if (strlen($friendNames[$i]) > 0)
{
if ($i > 0 )
{
$friendNamesQueryPart .= ",";
}
$friendNamesQueryPart .= "'".$friendNames[$i]."'";
}
}
if ($friendNamesQueryPart != NULL)
{
$sqlDiscard = "delete from friends
where requestId = ".$userId." and
providerId in (select Id from users where username in (".$friendNamesQueryPart."));
";
}
}
if ( ($sqlApprove != NULL ? $db->query($sqlApprove) : true) &&
($sqlDiscard != NULL ? $db->query($sqlDiscard) : true)
)
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
default:
$out = FAILED;
break;
}
echo $out;
///////////////////////////////////////////////////////////////
function authenticateUser($db, $username, $password, $port)
{
$sql = "select Id from users
where username = '".$username."' and password = '".$password."'
limit 1";
$out = NULL;
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$out = $row->Id;
$sql = "update users set authenticationTime = NOW(),
IP = '".$_SERVER["REMOTE_ADDR"]."' ,
port = ".$port."
where Id = ".$row->Id."
limit 1";
$db->query($sql);
}
}
return $out;
}
?>
and the second code is working on file upload
$base=$_REQUEST['image'];
echo $base;
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image'.time().'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
both the codes are working properly.
what i have tried to do is make another case in the switch statement in which the action is "filesharing"
Won't that work?
case "filesharing":$base=$_REQUEST['image'];
//echo $base;
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image'.time().'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
$out .= "Image upload complete!!, Please check your php file directory……";
break;
can anyone please give some suggestions?
So you have basically two files with two separate bits of functionality. The obvious solution would be to encapsulate each bit of code with a function i.e.
function query() {
/* your database query code here */
}
function file_upload() {
/* your file upload code here */
}
... and then encapsulate those functions in a class.
class MyCoolClass {
function query() {
/* your database query code here */
}
function file_upload() {
/* your file upload code here */
}
}
The advantages (and disadvantages) of Object Oriented Programming have been done to death, just have a google for it and you will undoubtedly find many wonderful, wonderful resources.