Creating a php web server in XAMPP - php

I am trying to create a web server in php by the help of XAMPP but my php has some Errors; I changed my localhost port from 80 to 85 i have added a MySQL database to my phpMyAdmin. I don't know why I am getting Error
Fatal error: Class 'MySQL' not found in C:\xampp\htdocs\chitchat\index.php on line 7
<?php
//Must change below variables to your ones
$dbHost = "localhost:85";
$dbUsername = "root";
$dbPassword = "";
$dbName = "chitchat";
$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 ($action == "testWebAPI")
{
if ($db->testconnection()){
echo SUCCESSFUL;
exit;
}else{
echo FAILED;
exit;
}
}
if ($username == NULL || $password == NULL)
{
echo FAILED;
exit;
}
$out = NULL;
error_log($action."\r\n", 3, "error.log");
switch($action)
{
case "authenticateUser":
if ($userId = authenticateUser($db, $username, $password))
{
// 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." ";
//$sqlmessage = "SELECT * FROM `messages` WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 ";
$sqlmessage = "SELECT m.id, m.fromuid, m.touid, m.sentdt, m.read, m.readdt, m.messagetext, u.username from messages m \n"
. "left join users u on u.Id = m.fromuid WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 ";
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
}
if ($resultmessage = $db->query($sqlmessage))
{
while ($rowmessage = $db->fetchObject($resultmessage))
{
$out .= "<message from='".$rowmessage->username."' sendt='".$rowmessage->sentdt."' text='".$rowmessage->messagetext."' />";
$sqlendmsg = "UPDATE `messages` SET `read` = 1, `readdt` = '".DATE("Y-m-d H:i")."' WHERE `messages`.`id` = ".$rowmessage->id.";";
$db->query($sqlendmsg);
}
}
$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 "sendMessage":
if ($userId = authenticateUser($db, $username, $password))
{
if (isset($_REQUEST['to']))
{
$tousername = $_REQUEST['to'];
$message = $_REQUEST['message'];
$sqlto = "select Id from users where username = '".$tousername."' limit 1";
if ($resultto = $db->query($sqlto))
{
while ($rowto = $db->fetchObject($resultto))
{
$uto = $rowto->Id;
}
$sql22 = "INSERT INTO `messages` (`fromuid`, `touid`, `sentdt`, `messagetext`) VALUES ('".$userId."', '".$uto."', '".DATE("Y-m-d H:i")."', '".$message."');";
error_log("$sql22", 3 , "error_log");
if ($db->query($sql22))
{
$out = SUCCESSFUL;
}
else {
$out = FAILED;
}
$resultto = NULL;
}
$sqlto = NULL;
}
}
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)
{
$sql22 = "select * from users
where username = '".$username."' and password = '".$password."'
limit 1";
$out = NULL;
if ($result22 = $db->query($sql22))
{
if ($row22 = $db->fetchObject($result22))
{
$out = $row22->Id;
$sql22 = "update users set authenticationTime = NOW(),
IP = '".$_SERVER["REMOTE_ADDR"]."' ,
port = 15145
where Id = ".$row22->Id."
limit 1";
$db->query($sql22);
}
}
return $out;
}
?>
SQL code:
CREATE TABLE [IF NOT EXISTS] friends (
Id int (10) NOT NULL AUTO_INCREMENT,
providerid int(10) NOT NULL AUTO_INCREMENT,
requestid int(10) NOT NULL AUTO_INCREMENT,
status binary(1) NOT NULL DEFAULT
PRIMARY KEY (Id));
CREATE TABLE [IF NOT EXISTS] messages AS (
id int(255) NOT NULL AUTO_INCREMENT,
fromuid int(255) NOT NULL,
touid int(255) NOT NULL,
sentdt datetime NOT NULL;
read tinyint(1) NOT NULL DEFAULT '0',
readdt datetime DEFAULT NULL,
messagetext longtext CHARACTER SET utf8 | NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE [IF NOT EXISTS] users (
Id int(10) unsigned NOT NULL AUTO_INCREMENT,
username varchar(45) NOT NULL DEFAULT '',
password varchar(32) NOT NULL DEFAULT '',
email varchar(45) NOT NULL DEFAULT '',
date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
status tinyint(3) unsigned NOT NULL DEFAULT '0',
authenticationTime datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
userKey varchar(32) NOT NULL DEFAULT '',
IP varchar(45) NOT NULL DEFAULT '',
port int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (Id)
)

change the line
$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName);
to
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);

It seems you erased a line from your file, similar to:
require_once("mysql.class.php");
you should add it before new MySQL(...) then you can use a class with name MySQL in your code.

Related

how to get valid json response from server

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

how to get the output in array using echo php

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;
}

how to display the query records in php

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;
}

Retrieve escaped data from the MySQL database

I am using StringEscapeUtils.escapeSql method of apaches lang library in my android app. I send http post requests to server to execute my SQL queries. While I am inserting the values there is no problem; I can insert the strings in escaped format.
But I can't retrieve the data from the database back to my android app. The strings that don't need to be escaped in the first place, I can retrieve with no problem. What should I do to retrieve the strings from database that I escaped before?
Here is part of my code:
PHP
case "authenticateUser":
if ($userId = authenticateUser($db, $username, $password))
{
$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." ";
$sqlmessage = "SELECT m.id, m.fromuid, m.touid, m.sentdt, m.read, m.readdt, m.messagetext, u.username from messages m \n"
. "left join users u on u.Id = m.fromuid WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 ";
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."'/>";
}
if ($resultmessage = $db->query($sqlmessage))
{
while ($rowmessage = $db->fetchObject($resultmessage))
{
$out .= "<message from='".$rowmessage->username."' sendt='".$rowmessage->sentdt."' text='".$rowmessage->messagetext."' />";
$sqlendmsg = "UPDATE `messages` SET `read` = 1, `readdt` = '".DATE("Y-m-d H:i")."' WHERE `messages`.`id` = ".$rowmessage->id.";";
$db->query($sqlendmsg);
}
}
$out .= "</data>";
}
else
{
$out = FAILED;
}
}
else
{
// exit application if not authenticated user
$out = FAILED;
}
break;
case "sendMessage":
if ($userId = authenticateUser($db, $username, $password))
{
if (isset($_REQUEST['to']))
{
$tousername = $_REQUEST['to'];
$message = $_REQUEST['message'];
$sqlto = "select Id from users where username = '".$tousername."' limit 1";
if ($resultto = $db->query($sqlto))
{
while ($rowto = $db->fetchObject($resultto))
{
$uto = $rowto->Id;
}
$sql22 = "INSERT INTO `messages` (`fromuid`, `touid`, `sentdt`, `messagetext`) VALUES ('".$userId."', '".$uto."', '".DATE("Y-m-d H:i")."', '".$message."');";
error_log("$sql22", 3 , "error_log");
if ($db->query($sql22))
{
$out = SUCCESSFUL;
}
else {
$out = FAILED;
}
$resultto = NULL;
}
$sqlto = NULL;
}
}
else
{
$out = FAILED;
}
break;
Java
public String sendMessage(String username, String tousername, String message) throws UnsupportedEncodingException
{
String params = "username="+ URLEncoder.encode(this.username,"UTF-8") +
"&password="+ URLEncoder.encode(this.password,"UTF-8") +
"&to=" + URLEncoder.encode(tousername,"UTF-8") +
"&message="+ URLEncoder.encode(message,"UTF-8") +
"&action=" + URLEncoder.encode("sendMessage","UTF-8")+
"&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}

how to merge two server codes written in php

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.

Categories