Trying to connect from iOS to MySQL Database using php ( HTTP POST ) - php

Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?

Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.

Related

Warning: mysqli::query(): Couldn't fetch mysqli in D:\wamp\www\site\admin\list.php on line 54 [duplicate]

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case

Warning: mysqli_query(): Couldn't fetch mysqli in <file> on line <number>

The view file
<?php
require('OrderModel.php');
session_start();
if(!isset($_SESSION['orderModel'])){
$newModel = new OrderModel();
$_SESSION['orderModel'] = $newModel;
} else{
$newModel = $_SESSION['orderModel'];
}
$newModel->addToBasket(1, 30);
echo $newModel->getItemName($newModel->basket[0][0]);
?>
The OrderModel file (simplified)
class OrderModel{
public $basket;
public $orderDate;
public $orderTime;
public $sent;
public $dbc;
public $customerOrderID;
public function __construct()
{
$this->dbc = require_once('../../db/config.php');
$this->basket = [];
}
public function addToBasket($itemNumber, $itemQuantity){
array_push($this->basket, [$itemNumber, $itemQuantity]);
}
public function getItemName($itemNum){
$query = "SELECT ItemName FROM item WHERE ItemID = $itemNum;";
$r = mysqli_query($this->dbc, $query); //Line 31
if($r){
return mysqli_fetch_row($r)[0];
}else{
echo mysqli_error($this->dbc); //Line 35
}
}
I can confirm that the config.php file is definitely configured correctly and is talking to the DB. In any rate, the code is:
<?php
define ('username', 'root');
define ('password', 'root');
define ('server', '127.0.0.1');
define ('database', 'alberto');
$dbc = mysqli_connect(server, username, password, database) OR DIE ('Could not connect to MySQL: ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
return $dbc;
?>
I am getting the following error messages from the view file:
Warning: mysqli_query(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 31
Warning: mysqli_error(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 35
I suspect the error is to do with the session, but I can't seem to find any answers from the threads posted so far.
Please kindly advise. Thank you.
Barmar is correct that $this->dbc is not a valid mysqli object. You are using the require_once with the file like a function. Make the config.php a class, and make the db connection from there. See here for an example of what I'm referring to. https://gist.github.com/jonashansen229/4534794

MYSQLI Error : Call to a member function execute() on a non-object [duplicate]

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case

Problems connecting to MySQL using PDO

I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'config.php';
// connecting to mysql
try {
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
}
catch (PDOException $e) {
$output = 'Unable to connect to database server.' .
$e->getMessage();
exit();
}
}
// destructor
function __destruct() {
}
public function getAllUsers() {
try {
$sql = "select * FROM gcm_users";
//$result = mysql_query("select * FROM gcm_users");
$result = $this->$db->query($sql);
return $result;
}
catch (PDOException $e) {
$error = 'Error getting all users: ' . $e->getMessage();
}
}
With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12
Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12
Line 12 is:
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
TYPO
//$this->$db =
$this->db =
same here
//$this->$db->query($sql);
$this->db->query($sql);
and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

Handling my connection variable for login script use [duplicate]

This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
Currently I am using
$con=mysqli_connect("x","x","x","x");
to handle my database connection on the login script. However, I'm trying to transition this to an OOP style approach such as
$con = new dbclass();
$con->openDB();`
I'm not having any luck with this though.
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 103
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 104
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 109
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\c\login.php on line 111
Acess denied, wrong username or password?
This is the method I'm using to do this.
function openDB() {
$config = include("/assets/configs/db_config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
// 1. Create a database connection
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Can anyone make any suggestions. Do I need to use mysqli_connect() somewhere within my method. Or even better, within my db_config file :
<?php
return array("host"=>"x", "dbname"=>"x", "username"=>"x", "password"=>"x");
mysqli_report(MYSQLI_REPORT_ERROR);
?>
include() does not cause the variables defined therein to become an array - they are automatically imported into the scope in which you are calling the function. Since you are not defining $config inside the include file, you're never accessing the array.
So, $config = include('your_script.php') doesn't do what you likely think it does.
You should update the function as follows (and change the array definition inside db_config.php to define $host, $username, $password and $dbname).
function openDB()
{
include("/assets/configs/db_config.php");
$conn = mysqli_connect($host, $username, $password, $dbname);
// 1. Create a database connection
if(!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
That having been said, this isn't the best way to handle DB connections in an OOP application. If you need to move the config file, you have to update the Database class. It would be better to pass in the variables to your openDB() function as parameters, and then retrieve them from a config script in your controller somewhere.
For example, the following is much better practice:
function openDB($username, $password, $dbname, $host = 'localhost')
{
$conn = mysqli_connect($host, $username, $password, $dbname);
if(!$conn)
{
$this->error_msg = 'connection error could not connect to the database!';
return false;
}
$this->conn = $conn;
return true;
}
Try using this only initiate like $db = new db(); no need to open db it will already connect
EDIT
here is code of db_config.php
$db_host = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'bs_admin';
class db
{
public $dbh;
public $error;
public $error_msg;
// Create a database connection for use by all functions in this class
function __construct()
{
require(dirname(dirname(__FILE__)) . '/config/db_config.php');
if($this->dbh = mysqli_connect($db_host, $db_user, $db_password, $db_name))
{
// Set every possible option to utf-8
mysqli_query($this->dbh, 'SET NAMES "utf8"');
mysqli_query($this->dbh, 'SET CHARACTER SET "utf8"');
mysqli_query($this->dbh, 'SET character_set_results = "utf8",' .
'character_set_client = "utf8", character_set_connection = "utf8",' .
'character_set_database = "utf8", character_set_server = "utf8"');
}
else
{
// Log an error if the connection fails
$this->error = true;
$this->error_msg = 'Unable to connect to DB';
}
// Add a row to any table
public function insert($table,$field_values)
{
$query = 'INSERT INTO ' . $table . ' SET ' . $field_values;
mysqli_query($this->dbh,$query);
}
}

Categories