Php webservice inserting data to a database - php

In my Authentication.php class I hava a code like below;
public function prepareTicket($data){
if(array_key_exists('tickettype', $data))
$this->tickettype = $data['tickettype'];
if(array_key_exists('ticketinfo', $data))
$this->ticketinfo = $data['ticketinfo'];
}
function createTicket(){
$sql = "INSERT INTO ticket_test (tickettype, ticketinfo) VALUES ('$this->tickettype','$this->ticketinfo')";
$result = mysqli_query($this->DB_CONNECTION,$sql);
}
function createTicketControl(){
$sql = "SELECT * FROM `ticket_test` WHERE tickettype = '".$this->tickettype."'AND ticketinfo ='".$this->ticketinfo."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
if(mysqli_num_rows($result) >0){
return true;
}else{
return false;
}
}
and in the other php file I have a code like this;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepareTicket($_POST);
$ticketStatus = $auth->createTicketControl();
if($ticketStatus){
$json['success'] = 1;
$json['message'] = 'Destek kaydı oluşturuldu';
}else{
$json['success'] = 0;
$json['message'] = 'Error!';
}
echo json_encode($json);
Now my problem is that whenever I try to insert data to my database it returns 'success' = '0' , 'message' = 'Error' and the data couldnt be inserted on the database.I mean the service is not working properly.Any help is appreciated...
P.S.= I am aware of sql injection threat on this code bu it is for android app so no need to worry about it.

Found the solution.I realised that in CreateTicket.php I didint call createTicket function from Authentication.php :/

Related

code works without error on localhost, but giving SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data on 000webhost

i am working on an python GUI application, and this part is back end of it. i am really unknown to JSON. and familiar with little bit of PHP. if possible, please give me the exact line of code where should i change it.
code giving SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
my local php version is v 8.1.12 is this a problem?
?
<?php
header('Content-type: application/json');
// Include database connector
include 'database_connector.php';
// test connection
if (isset($_POST['test_connection'])) {
$data['connection_response'] = "OK";
}
// check app key and id
if (isset($_POST['checkapp'])) {
$data['valid_app'] = False;
if (!isset($_POST['app_key']) or empty($_POST['app_key'])) {
$data['response_message'] = "Invalid app key";
}elseif (!isset($_POST['app_id']) or empty($_POST['app_id'])) {
$data['response_message'] = "Invalid app id";
}else{
if (checkAppKey($_POST['app_id'], $_POST['app_key'])) {
if (checkAppKeyExpiration($_POST['app_key'])) {
$data['response_message'] = "App key expired! Please login";
}else{
$data['response_message'] = "Valid app key and id";
$data['valid_app'] = True;
$userDetails = getAppUser($_POST['app_id']);
if(!empty($userDetails) && isset($userDetails['user_name'])){
$data['username'] = $userDetails['user_name'];
}else{
$data['username'] = "";
}
$appDetails = getAppDetails($_POST['app_id']);
if(!empty($appDetails) && isset($appDetails['key_expiration_date'])){
$data['expiry_date'] = $appDetails['key_expiration_date'];
}else{
$data['expiry_date'] = "unknown";
}
}
}else{
$data['response_message'] = "Invalid app id or key";
}
}
$data['app_id'] = $_POST['app_id'];
$data['app_key'] = $_POST['app_key'];
}
// view if app key already exists
function view_app_key($link)
{
global $dbh;
$sql = "SELECT * FROM `applications` WHERE `application_key`='".$link."'";
$query = $dbh->prepare($sql);
$query->execute();
$result = $query;
if ($row = $result->fetch( PDO::FETCH_ASSOC )){
return "true";
}else{
return "false";
}
}
echo json_encode($data);
?>
the full code is here: https://drive.google.com/file/d/1Q5qLAZW5qachxWuc4ibtDMCH5KochjuS/view
In your ajax call try this Simply change,
var respons = jQuery.parseJSON(response);
to
var respons = response;
Explanation:
If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().

PHP populate array inside a function

i have a small problem with my php code.
i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.
<?php
$returnData = array();
class Clients
{
public function readAll(){
$query = "SELECT * FROM clients";
$result = $this->con->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$returnData['clientsList'][] = $row;
}
return $returnData;
}
else{
echo "No found records";
}
}
}
if ($auth->isAuth()){
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientsObj->readAll();
}
echo json_encode($returnData);
?>
and the result is like that, but without clietslist
{
"message": "you are loggedin, so is ok"
}
Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.
You need to get return value of function in a variable:
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] = $clientsObj->readAll();
$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.
I suggest you to read about variable scope in php.
https://www.php.net/manual/en/language.variables.scope.php
Now, You will need to store returned value from function in a variable
like this
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray = $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];

how to avoid duplicate data with php

How do I avoid duplicate data when we enter the same data again? instead, I want to issue a warning:
sorry your username has been used
I'm using php script, I have done it to overcome duplicate data but the results have unexpected errors.
This is my code, please correct it if you wish. thanks
<?php
if (isset($_POST['submit'])) {
$npm_siswa = $_POST['npm_siswa'];
$nama_siswa = $_POST['nama_siswa'];
$bidangst_siswa = $_POST['bidangst_siswa'];
$ipk_siswa = $_POST['ipk_siswa'];
$query ="INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$insert_data = mysqli_query($con, $query);
$goto = header('location: input_data.php');
if (headers_sent($goto) == true) {
exit();
}
}
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
while($row_filter = mysqli_fetch_assoc($process)) {
$kelasId = $row_filter['kelasId'];
$npm_siswa = $row_filter['npm_siswa'];
$nama_siswa = $row_filter['nama_siswa'];
$bidangst_siswa = $row_filter['bidangst_siswa'];
$ipk_siswa = $row_filter['ipk_siswa'];
}
if (mysqli_num_rows($process) > 0) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
?>
The easy way is to first select rows from mysql using a select statement, and then check if the array is empty.
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
if(empty($process)) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
Another solution: make sure that it is the DBMS that controls the uniqueness, with a UNIQUE constraint. Then test your mysqli_query's return value to handle the error.
$process = mysqli_query($con, $checking);
if (!$process)
{
// Handle your error
}
Pros : Only one query
Cons : The error is not necessarily due to the UNIQUE constraint

Failed to load resource: the server responded with a status of 500 (Internal Server Error) web server php

<?php
require("MySQLDAO.php");
$config = parse_ini_file('../database.ini');
$returnValue = array();
//checking if the information is not empty.
if(empty($_REQUEST["firstname"]) || empty($_REQUEST["lastname"])
|| empty($_REQUEST["address"])|| empty($_REQUEST["postcode"])|| empty($_REQUEST["userid"])){
$returnValue["error"]="Missing information";
$returnValue["message"]="You have not added all the information needed to sign up.";
echo json_encode($returnValue);
return;
}
//protect from sql injections.
$fn = htmlentities($_REQUEST["firstname"]);
$ln = htmlentities($_REQUEST["lastname"]);
$add = htmlentities($_REQUEST["address"]);
$post = htmlentities($_REQUEST["postcode"]);
$userid = htmlentities($_REQUEST["userid"]);
// read ini file which has the keys.
$dbhost = trim($config["dbhost"]);
$dbuser = trim($config["dbuser"]);
$dbpass = trim($config["dbpass"]);
$dbname = trim($config["dbname"]);
$dao = new MySQLDAO($dbhost,$dbuser,$dbpass,$dbname);
$dao ->openConnection();
$userdetails = $dao->postAccDetail($userid);
if (!empty($userdetails))
{
$returnValue["error"]="Error 101";
$returnValue["message"]="You have already submitted to get your accounts through the post.";
echo json_encode($returnValue);
return;
}
//register new user.
$result = $dao ->registerPost($fn,$ln,$add,$post,$userid);
if($result){
$returnValue["Message1"] = "Congratulations!";
$returnValue["Message2"] = "We will be sending your details to you in the next 5 working days.";
}
else{
$returnValue["error"] = "Something went wrong";
$returnValue["Message"] = "Sorry we could not create a profile for you please try again.";
}
$dao ->closeConnection();
echo json_encode($returnValue);
?>
<database file>
public function postAccDetail($userid) {
$returnValue = array();
$sql = "select * from post where userid ='".$userid."'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
public function registerPost($fn,$ln,$add,$post,$userid) {
$sql = "insert into post set firstname=?,lastname=?,address=?,postcode=?,userid=?";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
//the 5s indicate that the values are going to be strings.
$statement->bind_param("ssssi",$fn,$ln,$add,$post,$userid);
$returnValue = $statement->execute();
return $returnValue;
}
I can't seem to find an error with this code and was wondering if someone could help. when I run the file on my local machine I seem to be fine but when I upload the files to a server I seem to get a failed to load resource i know the database file is correct as other files seem to work fine without a problem.
I've added an image of the database aswell.
Can someone please help me.

display data from phpmyadmin

I'm a beginner in PHP5 and I'would like to have some help to get the code correct. Check the code and I'will be grateful for your support.
index.php:
if ($tag == 'AfficherMesAnnonce')
{
$Id_Utilisateur= $_GET['Id_Utilisateur'];
$annonce = $db->MesAnnonces($Id_Utilisateur);
if ($annonce)
{
$response["success"] = 1;
$response["annonce"]["Departure_place"] =$annonce["Departure_place"];
$response["annonce"]["Departure_date"] = $annonce["Departure_date"];
$response["annonce"]["Arrival_place"] = $annonce["Arrival_place"];
$response["annonce"]["Path_type"] = $annonce["Path_type"];
echo json_encode($response);
// annonce stored successfully
}else
{
$response["error_msg"] ="No annonce found";
return false;
echo json_encode($response);
}
}
DB_Function.php:
public function MesAnnonces($Id_Utilisateur)
{
$result = mysql_query("SELECT * FROM annonce WHERE Utilisateur_Id_Utilisateur = $Id_Utilisateur") or die(mysql_error());
// check for result
while($row = mysql_fetch_assoc($result))
{
$dd[]=$row;
}
$response=array('annonce'=> $dd);
return $response;
}
and thank you in advance.
You DB function is creating the dd array as a collection of rows, and then nesting that as an element of what's returned. But in your calling script you're assigning
$response["annonce"]["Departure_place"] = $annonce["Departure_place"]
--but the right side of that doesn't exist. You could instead assign:
$response["annonce"]["Departure_place"] = $annonce[0][0]["Departure_place"]
which would be the first row. You're not iterating through the rows in the client script, or using any kind of index to select a row.

Categories