Delete query is not working in PHP - php

I am trying to delete a particular id from a table in PHP. I have written two queries in the same php.
something like this:
<?php
include("db.php");
$response = array();
if (isset($_POST['userID']))
{
$userID = $_POST['userID'];
$result1 = mysql_query("DELETE FROM profile WHERE userID = '$userID'");
$result2 = mysql_query("DELETE FROM profile_details WHERE userID = '$userID'");
if ($result1 && $result2 )
{
$response["success"] = 1;
$response["message"] = "row successfully created.";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
}
else
{
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
I get the following error:
Parse error: syntax error, unexpected '$result1' (T_VARIABLE) in /homepages/htdocs/radiansa.com/extras/a/test2.php on line 16
I am not sure what could be wrong here..

First of all... stop using mysql_ and switch to PDO or mysqli_. The old ext/mysql mysql_*() functions were deprecated in PHP 5.5 and will eventually be removed entirely.
This needs attention also. Too vulnerable to anything.
$userID = $_POST['userID'];
For your problem, now. Change:
$result = mysql_query("xxxxxxx");
to
$result = mysql_query("xxxxx") or die(mysql_error());
It will help you debug your problem and point you to the right direction

Related

Returning JSON message in PHP

I have written a PHP script to connect to a MySQL database and extract some information. I know that the majority of the script is working as it actually inserts a MAC address into the table (which is what it should do when the value of the MAC address in the DB table is NULL).
However, the resulting message from my script is "No license found (3)".
My question is, how can it be returning this message if it's inserting a MAC address? The else statement would only be entered if if (mysqli_num_rows($result) > 0) returned false.
What I want is for the MAC address to be checked (or inserted if NULL in the DB) and to return the message "Licensed".
Apologies for the nested if/else statements.
<?php
// Array for JSON response.
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
// Check for GET data.
if (isset($_GET["LicenseKey"])
&& isset($_GET["SoftwareId"])
&& isset($_GET["MacAddress"])) {
$licenseKey = $_GET['LicenseKey'];
$softwareId = $_GET['SoftwareId'];
$macAddress = $_GET['MacAddress'];
// Import database connection variables.
require_once __DIR__ . '/get_license_SQL.php';
$query = SQL_GET_LICENSE;
$query = str_replace("%1", $softwareId, $query);
$query = str_replace("%2", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
// Check for empty result.
if (mysqli_num_rows($result) > 0) {
// Get the result.
$result = mysqli_fetch_array($result);
$license = array();
$license["ExpiryDate"] = $result["ExpiryDate"];
// Check if MAC address exists.
$query = SQL_GET_MAC_ADDRESS;
$query = str_replace("%1", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
$result = mysqli_fetch_array($result);
echo json_encode($result);
if ($result["MacAddress"] == $macAddress
|| $result["MacAddress"] == NULL) {
// Device MAC address matches MAC address on record.
$response["success"] = 1;
$response["license"] = array();
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
$response["message"] = "Licensed";
array_push($response["license"], $license);
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "License has already been used by another device";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (2)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (3)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (4)";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
db_connect.php :
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
return $con;
}
}
?>
get_license_SQL.php :
<?php
define('SQL_GET_LICENSE', "SELECT licenses.ExpiryDate
FROM licenses
WHERE licenses.SoftwareId=%1 AND licenses.LicenseKey=%2");
define('SQL_GET_MAC_ADDRESS', "SELECT licenses.MacAddress
FROM licenses
WHERE licenses.LicenseKey=%1");
define('SQL_INSERT_MAC_ADDRESS', "UPDATE licenses
SET MacAddress=%1
WHERE licenses.LicenseKey=%2");
?>
Please look at the following lines of code
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
You are running the following query but you are not storing the result in a variable after insertion in the database:
mysqli_query($db->connect(), $query);
In the following line the $result array has the old values from the database which were fetched prior to insertion. Please try to store the values in a variable and use that variable after the insertion.
$license["MacAddress"] = $result["MacAddress"];

Issues with JSON in PHP

I am trying to create a restAPI to get some details from MySQL for this I have created a PHP file to access them on Android devices.
Here is the PHP file:
<?php
include("db_details.php");
$response = array();
if (isset($_POST['userID']))
{
$userID = $_POST['userID'];
$grantedvalue = "granted";
$stmt = mysqli_prepare($bd, "SELECT p.name, p.userURL, a.grantaccuracy FROM loc_details d JOIN loc_profile p ON d.userID = p.userId JOIN loc_friends a on a.userId = d.userId WHERE a.grantstatus = ? and a.grantuserID = ?");
mysqli_stmt_bind_param($stmt, "ss", $grantedvalue, $userID);
$checkresult = mysqli_stmt_execute($stmt);
$result = $stmt->get_result();
if (!$checkresult)
{
die("Error updating user_details_table: " . mysqli_stmt_error($stmt));
}
else
{
echo $result -> num_rows;
if($result -> num_rows > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
// temp user array
$detail = array();
$detail["name"] = $row["name"];
$detail["userURL"] = $row["userURL"];
$detail["grantaccuracy"] = $row["grantaccuracy"];
array_push($response["details"], $detail);
}
$response["success"] = 1;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Zero Data";
echo json_encode($response);
}
}
}
else
{
$response["success"] = 300;
$response["message"] = "issue with getting values";
echo json_encode($response);
}
?>
I am using AsyncHttpClient Library to access the above php file. The results are not coming up there but when I try to access the php directly on browser something like this:
http://www.thiswillhavemycompanydomain.com/loc/get_user_details.php?userID=2238
The results are getting printed correctly on the browser. So I thought it could be an issue with coding part in android hence I tried using the Chrome Extension (Advance REST CLIENT) to see if I can get the results.. Strangely I am not getting results even there. I am always getting the else part of if (isset($_POST['userID'])) from the php code.
Not sure what could be wrong here as I can view all the data on my browser directly but not on ARC or my android APP?
Can somebody help me fix this as I don't know where could be the problem?
Thanks!

MySQL like Query fails in PHP

$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die mysql_error();
The error i get is
Parse error: syntax error, unexpected T_STRING in /home/maximtec/public_html/masjid_folder/MasjidFinderScripts/find_by_name.php on line 24
This query does work when i use it in MySQL but it doesn't when I place it in a PHP Script
Please suggest a solution
------------EDIT :After changing query from the received answers-------------------------------------
Well I updated my query but now I am getting null results
{"masjids":[{"MasjidName":null,"Address":null,"Latitude":null,"Longitude":null}],"success":1,"masjid":[]}
Following is my full script :
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
//require_once __DIR__ . '/db_connect.php';
require_once dirname(__FILE__ ). '/db_connect.php';;
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["MasjidName"])) {
$MasjidName = $_GET['MasjidName'];
// get a product from products table
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
$response["masjids"] = array();
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$row = mysql_fetch_array($result);
$masjid = array();
$masjid["MasjidName"] = $row["MasjidName"];
$masjid["Address"] = $row["Address"];
$masjid["Latitude"] = $row["Latitude"];
$masjid["Longitude"] = $row["Longitude"];
// success
$response["success"] = 1;
// user node
$response["masjid"] = array();
array_push($response["masjids"], $masjid);
// array_push($response["masjid"], $masjid);
}
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
A little more tweaking, for good practice wrap table names and table columns in ``.
You also shouldn't need () around ('%moh%')
Try this-
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die(mysql_error());
You forget parentheses with die(mysql_error())
try this:
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE '%moh%' ") or die(mysql_error());
use die() like this die(mysql_error()) .

PHP doesnt display anything

Hi guys I'm new to PHP and I'm trying to display all info in my admin table. When I test my PHP file it gives me a blank page, here is my php code. There's no error but I get a blank page and nothing was returned when I execute it.
<?php
require('connect.inc.php');
require('admin.config.inc.php');
require('core.inc.php');
if (!empty($_POST)) {
//initial query
$query = "SELECT * FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["users"] = array();
foreach($rows as $row) {
$user = array();
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["users"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
Put this at the head of the script to see what response you get. Then others may be able to help you according to the error you get.
ini_set('display_errors',1);
error_reporting(E_ALL);
I see you have also began with:
if (!empty($_POST)) {
}
$_POST IS An associative array of variables passed to the current script via the HTTP POST method.
$_POST is defined where. this should be some thing like $_POST['user']
You begin with:
if (!empty($_POST)) {
which is empty by default, so you go directly to the else statement which is empty as well!
You are declaring $user = array(); inside the loop, It has to be outside of the loop
$user = array();
foreach($rows as $row) {
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];

PHP Select Value in MySQL Using Greater Than and Less Than

I have been racking my brains trying to get something that seems simple to work. I have a TABLE "weight". Weight has 3 columns "shipping_to", "shipping_from", and "shipping_cost".
Shipping_to and Shipping_from are the weight values and shipping cost holds the shipping cost if the value is greater than or equal to X AND less than or equal to X.
I have written this a million different ways and for the life of me it won't work.
UPDATED:
The Script works "kind of" but it never returns a success response of 1 and it never fimds the value of X even though I have manually put these values into my MySQL db.
PHP SCRIPT:
if($The_Function=="SHIPPING_COST"){
$response = array();
require_once __DIR__ . '/db_connect.php';
$con = new DB_CONNECT();
$ship_weight = 1;
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if(!empty($result)){
if (mysql_num_rows($result) > 0) {
$response["userID"] = array();
while ($row = mysql_fetch_array($result)) {
$custID = array();
$custID["shipping_cost"] = $row["shipping_cost"];
array_push($response["userID"], $custID);
}
$response["success"] = 1;
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}
The error was in the Query itself. All I had to do was give the last Column something to compare to so I just added $ship_weight again. Here is the code.
$result = mysql_query("SELECT * FROM weight WHERE '$ship_weight' >= from_weight AND '$ship_weight' <= to_weight");
I think the problem is that $result will never be empty()
If the query works if will be a resource handle and if it fails it will be false.
So try this:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if($result !== FALSE){
if (mysql_num_rows($result) > 0) {
$response["userID"] = array();
while ($row = mysql_fetch_array($result)) {
$custID = array();
$custID["shipping_cost"] = $row["shipping_cost"];
array_push($response["userID"], $custID);
}
$response["success"] = 1;
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
Is this a copy and paste of your code? If so, look at this line:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
PHP is considering your $ship_weight variable as part of the string. Change it to:
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '".$ship_weight."' AND to_weight <= '".$ship_weight."'");
Also, mysql_* is deprecated. Take a look at the mysqli_* extension.

Categories