How to write to mysql database? - php

I used localhost and everything works fine, however, when I hosted it in digital ocean, certain POST functions don't write to the mysql database.
I've tried using Postman to test the code, and it returns 200 OK and error writing to database.
My db_functions code:
public function insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree)
{
$stmt= $this->conn->prepare("INSERT INTO `Longhouses`(`Name`, `Link`,`Price`,`ListingId`,`descriptions`,`PackageOne`,`PackageTwo`,`MoreDescription`,`Itinerary`,`ImageTwo`,`ImageThree`) VALUES (?,?,?,?,?,?,?,?,?,?,?)") or die ($this->conn->error);
$stmt->bind_param("sssssssssss",$name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
$result = $stmt->execute();
$stmt->close();
if($result)
return true;
else
return false;
}
My add_listing function:
<?php
require_once '../../db_functions.php';
$db = new DB_Functions();
if(isset($_POST['name'])&&isset($_POST['imgPath'])&&isset($_POST['price'])&&isset($_POST['listingId'])&&isset($_POST['descriptions'])&&isset($_POST['packageOne'])&& isset($_POST['packageTwo'])&&isset($_POST['moreDescriptions'])&& isset($_POST['itinerary'])&& isset($_POST['imgPathTwo'])&& isset($_POST['imgPathThree']))
{
$name = $_POST['name'];
$imgPath = $_POST['imgPath'];
$price = $_POST['price'];
$listingId = $_POST['listingId'];
$descriptions = $_POST['descriptions'];
$packageOne = $_POST['packageOne'];
$packageTwo = $_POST['packageTwo'];
$moreDescriptions = $_POST['moreDescriptions'];
$itinerary = $_POST['itinerary'];
$imgPathTwo = $_POST['imgPathTwo'];
$imgPathThree = $_POST['imgPathThree'];
$result = $db->insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
if($result)
echo json_encode("ADD LISTING SUCCESFUL");
else
echo json_encode("error writing to database");
}

Related

im failing to connect to my website database via php

So i was following a tutorial on how i can create a website with a database using php and wamp
and am failing on connecting my website to my database
this is the code i wrote
<?php
require ("Entities/CoffeeEntity.php");
class CoffeeModel {
function GetCoffeeTypes() {
require 'Credentials.php';
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$result = $mysqli->query("Select a distinct Cofffee");
$types = array();
while ($row = $result->fetch_assoc()) {
array_push($types, $row[0]);
}
mysql_close();
return $types;
}
function GetCoffeeByType($type) {
require 'Credentials.php';
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT * FROM coffee WHERE type LIKE '$type'";
$result = $mysqli->query("error");
$coffeeArray = array();
while ($row = $result->fetch_assoc()) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$roast = $row[4];
$country = $row[5];
$image = $row[6];
$review = $row[7];
$coffee = new CoffeeEntity(-1, $name, $type, $price, $roast, $country, $image, $review);
array_push($coffeeArray, $coffee);
}
mysql_close();
return $coffeeArray;
}
}
?>
and this is the error that i get
Edit:
ok so i figured out that i need to replace mysql to mysqli
and i tried but it still seems not working cause i guess am doing something wrong
this is the result i came through
<?php
require ("Entities/CoffeeEntity.php");
//Contains database related code for the Coffee page.
class CoffeeModel {
//Get all coffee types from the database and return them in an array.
function GetCoffeeTypes() {
require 'Credentials.php';
//Open connection and Select database.
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$result = $mysqli->query("Select a distinct Cofffee");
$types = array();
//Get data from database.
while ($row = $result->fetch_assoc()) {
array_push($types, $row[0]);
}
//Close connection and return result.
mysql_close();
return $types;
}
//Get coffeeEntity objects from the database and return them in an array.
function GetCoffeeByType($type) {
require 'Credentials.php';
//Open connection and Select database.
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT * FROM coffee WHERE type LIKE '$type'";
$result = $mysqli->query("error");
$coffeeArray = array();
//Get data from database.
while ($row = $result->fetch_assoc()) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$roast = $row[4];
$country = $row[5];
$image = $row[6];
$review = $row[7];
//Create coffee objects and store them in an array.
$coffee = new CoffeeEntity(-1, $name, $type, $price, $roast, $country, $image, $review);
array_push($coffeeArray, $coffee);
}
//Close connection and return result
mysql_close();
return $coffeeArray;
}
}
?>
and this error shows up
can someone please help and make it work (sorry am really bad at this )
The query() method returns false one failure, see: https://www.php.net/manual/en/mysqli.query.php
You must check the method's result before calling fetch_assoc().
Your query is failing because the first argument of the method must be a valid query while you are passing the string error, because of that you are trying to call a method on a boolean.
Try changing line 36 with $result = $mysqli->query($query);

Cant call stored procedure from PHP

Can someone point out whats wrong with my php code for calling stored procedure in mssql. The following sql query works fine in mssql studio:
EXEC updateRecord 'Record','Closed','Jon','query test4','',''
Here is the php code that Im using to try and call the updateRecord:
<?php
$Record = $_POST['record'];
$Stat = $_POST['Status'];
$Tech = $_POST['Tech'];
$Action = $POST['Action'];
$Date = date("Y/m/d");
$time = date("G:i:s");
//connect to sql
$hostname = '127.0.0.1\SQLserver';
$options = array('Database'=>'CallHistory', 'CharacterSet' => 'UTF-8');
$conn = sqlsrv_connect($hostname, $options);
if(!is_resource($conn))
{
echo 'Could not connect: ';
var_dump(sqlsrv_errors(SQLSRV_ERR_ALL));
exit(0);
}
// echo "Success";
// sqlsrv_close($conn);
// DB queries
if (empty($_POST['record']) && empty($_POST['Statut'])&&empty($_POST['Tech']) && empty($_POST['Action']))
{
echo "CHoose at least one";
}
else
{
$query1 = "exec updateRecord $Record,$Stat,$Tech,$Action,$Date,$time";
}
$ask = sqlsrv_query($conn, $query1);
sqlsrv_fetch($ask);
.........
?>
What am I forgetting....?
The server seems to return an empty response and the actual record is not updated.
got it to work:
$query1 = "EXEC updateRecord #Record = '$Record', #Status = '$Stat', #Tech = '$Tech', #Date = '$Date', #time = '$time', #Actions = '$Action'";
thanks to this: https://stackoverflow.com/a/44911709

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"];

PHP PDO Insert Into statement doesn't work with no errors

At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?

PDO CRU are not functioning

I need your help figuring this out. I am trying to have a reserve a book functionality in my project. I don't have any error with this one but my oop functions that contains the pdo statements won't work. Particulary with the insert (values can't be inserted into the database) and update(can't update existing info from the database) part. I don't know why this happens.
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve($id,"book_info");
if(isset($_POST['reserve']))
{
foreach($result as $row)
{
echo $oldstock=$row['quantity'];
}
echo $newstock = $oldstock-1;
$code->minusbookreserve($quantity, $newstock,"book_info");
$code->insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,"reserve_list");
// echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
else {
echo "<script type='text/javascript'>alert('Something went wrong.');window.location='bookReservelist.php';</script>";
}
?>
codex_books.php
public function minusbookreserve($quantity, $newstock, $table)
{
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
if($stmt){
return true;
}
else {
return false;
}
}
public function insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,$table)
{
$q = "INSERT INTO $table SET sid= :sid ,sname=:sname,title=:title,author=:author,isbn=:isbn,publisher=:publisher,language=:language, genre=:genre, quantity=:quantity, date_to_be_borrow=:date_to_be_borrow";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':sid'=>$sid,':sname'=>$sname,':title'=>$title,':author'=>$author,':isbn'=>$isbn,':publisher'=>$publisher,':language'=>$language, ':genre'=>$genre,':quantity'=>$quantity,':date_to_be_borrow'=>$date_to_be_borrow));
return true;
}
Given:
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
^^^^^^^^^^^
Where's book_title here?
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
You really MUST check return values from your DB calls for boolean FALSE, indicating failure. You're simply assuming everything will always succeed, which is a very BAD way of writing code.

Categories