Echo data not being displayed - php

I am new to php development.I have created a database using phpmyadmin.Now i want all the data to be displayed on the page.But when ever i try to run the file nothing is showing up.I dont know why this is happening.
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesreview"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error($con));
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error($con));
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Code
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$con=new db_connect();
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
while($row=mysqli_fetch_array($result)){
$row_array['movies_id']=$row['movies_id'];
$row_array['movies_name']=$row['movies_name'];
$row_array['movies_description']=$row['movies_description'];
$row_array['movies_time']=$row['movies_time'];
$row_array['movies_release_date']=$row['movies_release_date'];
$row_array['movies_youtube_link']=$row['movies_youtube_link'];
$row_array['recent_upcoming']=$row['recent_upcoming'];
$row_array['movies_image']=$row['movies_image'];
$row_array['movies_actors']=$row['movies_actors'];
array_push($response,$row_array);
}
echo json_encode($response);
?>
Error what i am getting

There are a few things wrong with your code.
The space between <? and php
A missing tick for your table, and a missing semi-colon for your query.
A missing DB connection link.
Your code:
<? php
^ space
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0"
^ ^
$result=mysqli_query($strQuery);
^ no DB connection
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails` WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
Using error reporting http://php.net/manual/en/function.error-reporting.php would have signaled that, including or die(mysqli_error($con)) to mysqli_query()
You've edited your question. You are mixing mysqli_ and mysql_ functions. They do not mix.
All mysql_error should be mysqli_error($con) and mysql_close() to mysqli_close($con)
Edit:
Replace the entire contents of db_connect.php with the following:
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesdetails"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
Edit #2:
while($row=mysqli_fetch_array($result)){
$response[] = $row;
$row['movies_id'];
$row['movies_name'];
$row['movies_description'];
$row['movies_time'];
$row['movies_release_date'];
$row['movies_youtube_link'];
$row['recent_upcoming'];
$row['movies_image'];
$row['movies_actors'];
}
echo json_encode($response);

You have missing connection link as parameter in your mysqli_query() function. Should be:
$result = mysqli_query($connection_link, $strQuery);
http://php.net/manual/en/mysqli.query.php
$connection_link will have in this case following format:
// include db connect class
require_once __DIR__ . '/db_connect.php';
$connection_link = new DB_CONNECT();
But as #Fred -ii- said in comments, you have some syntax errors in PHP and SQL query too.
Your DB class is badly designed, you should store connection link in property and making queries through this class.

Related

Connect to Azure Database using Azure Web App

I'm trying to connect to my Azure sql database using following code:
<?php
//Constants to connect with the database
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'xyz-server.database.windows.net');
define('DB_NAME', 'xyz_db');
<?php
//Class DbConnect
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
I'm getting this error
Type: ErrorException
Code: 2
Message: mysqli::__construct(): (HY000/9002): The connection string may not be right. Please visit portal for references.
File: /home/site/wwwroot/blingoo/include/DbConnect.php
Line: 22
I'm just beginning with Azure. Maybe I'm missing something. If you could simply point how to connect my database and web app(where I'm using php files to connect to the database), that will be great.
Seems to me that your code is trying to connect to MySQL rather than MSSQL.
To connect to MSSQL use the following:
<?php
$serverName = "your_server.database.windows.net"; // update me
$connectionOptions = array(
"Database" => "your_database", // update me
"Uid" => "your_username", // update me
"PWD" => "your_password" // update me
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
FROM [SalesLT].[ProductCategory] pc
JOIN [SalesLT].[Product] p
ON pc.productcategoryid = p.productcategoryid";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
echo (sqlsrv_errors());
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
}
sqlsrv_free_stmt($getResults);
?>
source: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-php
Since you are trying to connect to Azure SQL you can use PDO_DBLIB driver, if you have this extension installed. See php -m.
$config = [
'dsn' => 'dblib:host=xyz-server.database.windows.net;dbname=xyz_db',
'user' => 'username',
'pass' => 'password',
];
$connection = new PDO($config['dsn'], $config['user'], $config['pass']);
$sth = $connection->prepare('Your query comes here;');
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_CLASS);
foreach ($rows as $row) {
// Do the processing here
}

Access denied error on php

I have 3 php files to connect phpmyadmin database.
Content of /Android/db_connect.php:
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Content of /Android/db_config.php:
<?php
/*
* All database connection variables
*/
define('DB_USER', "u155019120_movie"); // db user
define('DB_PASSWORD', "xxxxxxxxx"); // db password (mention your db password here)
define('DB_DATABASE', "u155019120_movie"); // database name
define('DB_SERVER', "mysql.hostinger.web.tr"); // db server
?>
Content of /publichtml/get_all_products:
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/../Android/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
When i open http://moviestolike.pe.hu/get_all_products.php page (also you can view), it says
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/u155019120/Android/db_connect.php on line 28
{"products":[{"pid":"1","name":"sogan","price":"19.30","created_at":"2016-03-12 15:08:38","updated_at":"0000-00-00 00:00:00"},{"pid":"2","name":"faltak","price":"22.00","created_at":"2016-03-12 15:08:38","updated_at":"0000-00-00 00:00:00"}],"success":1}
it gives right products. But when i change the deprecated method as
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
in first file i wrote here, the output is
Deprecated: mysql_select_db(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/u155019120/Android/db_connect.php on line 31
Access denied for user ''#'10.2.1.37' to database 'u155019120_movie'
What is wrong? I don't even know what 10.2.1.37 is. My username is what i wrote here.
Also i cant change mysql_select to mysqli_select, it wants one more parameter.
Correct syntax for mysqli_connect
mysqli_connect(host,username,password,dbname,port,socket);
port and socket fields are optional you can ignore those two by using it as
mysqli_connect(host,username,password,dbname);

mysqli_query() expects parameter 1 to be mysqli, object given in [duplicate]

This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
I got this error when i try to save database in mysql using wampServer.
mysqli_query() expects parameter 1 to be mysqli, object given in
there are 3 PHP files, db_config.php and db_connect.php and create_person.php and i already reated table PERSON in phpmyadmin.
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "othmane"); // database name
define('DB_SERVER', "localhost"); // db server
?>
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysqli_close();
}
}
?>
create person.php :
<?php
/*
* Following code will create a new person row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['nom']) && isset($_POST['pass_world'])) {
$name = $_POST['nom'];
$pass = $_POST['pass_world'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
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);
}
?>
Your
$db = new DB_CONNECT();
returns an instance of DB_CONNECT class.
What you need in your
mysqli_query(...)
call is the object returned by your mysqli_connect call.
Try changing your:
function __construct() {
// connecting to database
$this->connect();
}
with:
function __construct() {
// connecting to database
$this->conn = $this->connect();
}
Then, change:
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
with:
$result =mysqli_query($db->conn,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
Also, I think you should read the PHP manual for the functions you are using:
mysqli_connect
mysqli_select_db

Unknown MySQL server host 'DB_HOST' (0)

I am trying to sent data to the server database, i implement it using wamp server it was working fine but when i installed the db on my domain and switched it to my domain its giving the following error.
I have kept my files inside a folder in root directory
Unknown MySQL server host 'DB_HOST' (0)
Below is my config file i am using to connect to the db
<?php
// Database configuration
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'xxxx');
define('DB_HOST', '192.210.195.245');
define('DB_NAME', 'tabanico_userlogin');
?>
here my code connecting db, config.php file contains the code pasted above
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
and my file receiving data
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO login(id,name,email,password) VALUES('$id','$name','$email','$password')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = "Prediction added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add prediction!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
I have seen related post but didn't find useful answers. Can anyone help me in getting out of this. Thanks in advance.
Please post the code where you try to connect to the server. I guess you tried to connect using the following function:
mysql_connect('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD');
Since you defined the host using define('DB_HOST', 'localhost');, you do not have to use apostrophes. DB_HOST is a constant here. So try to use to
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
instead. If you use apostrophes like in 'DB_HOST', it is interpreted as a string instead of the value of the constant DB_HOST containing localhost. That's a possible reason why you get the error that DB_HOST is an unknown host.
But please post the connection part of your code to see if that's really the mistake.

PHP webservice require file error

I'm trying to create a webservice with PHP and MySQL but I get errors when I try to require files. Here's my code:
db_config.php
<?php
define('DB_USER', "a1605031_test2");
define('DB_PASSWORD', "******");
define('DB_DATABASE', "a1605031_test2");
define('DB_SERVER', "mysql13.000webhost.com");
?>
DB_CONNECT.php
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
return $con;
}
function close() {
mysql_close();
}
}
?>
test.php
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
?>
But when I open test.php I get this
require_once() [function.require]:
Failed opening required '__DIR__/db_connect.php' (include_path='.:/usr/lib/php:/usr/local/lib/php')
in /home/a1605031/public_html/test2/test.php on line 2
So how should I require the file ? I'm using 000webhost.com, if it matters.
What version of PHP is installed? It looks like __DIR__ isn't defined - which was added in PHP 5.3. Try this instead:
require_once dirname(__FILE__) . '/db_connect.php';

Categories