Php query over wordpress db doesn't work - php

I try to query the wordpress database from a standalone php file named test.php and located on the root folder of the wp installation folder, but the query return nothing to be displayed, the var dump show nothing, what i do wrong and how to test if the hosting support mysqli?(credentials has been removed from db connection)
enter image description here
<?php
$mysqli = new mysqli('localhost', 'username', 'passwd', 'dbname');
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$result = $mysqli->query("select meta_value from wpde_postmeta where meta_key = '_product_attributes' and post_id = '41'") ;
echo $result;
var_dump($result);
/* free result set */
$result->close();
$mysqli->close();
?>

You're missing the data fetch part:
// Just below $result = $mysqli->query("...") ;
while($obj = $result->fetch_object()){
// Do something with $obj->meta_value
}

Related

Using php I need to have 2 different connections to the database

I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);
you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');
I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql

php parent page redirect twice after using header location

I am stuck with my php code. Parent php page reload again after header() works, Here is my code
<?php
$mysqli = new mysqli("localhost", "root", "root", "testing");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$sql ="update test set hit_count = hit_count+1";
$result = $mysqli->query($sql);
header('Location: http://www.google.com/');
die();
?>
Here some times i got 2 hit_count from db.
How it works, i added die() after header().
You should not output text before using header redirects as seen on the code below:
/* Select queries return a resultset */
if ($result = $mysqli->query($sql)) {
printf("updated");
}else{
echo "failed";
}

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);

PHP page doesn't load the data from my MySQL database on 123-reg

I am trying to setup a connection to my MySql database via a php page which is hosted on 123-reg. The PHP page is "http://domainName.biz/android_connect/get_all_bars.php" which at the moment the page comes up blank?
The code for that page is as follows:
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM pubbar");
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["pubbar"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$pubbar = array();
$pubbar["Pubbar_ID"] = $row["Pubbar_ID"];
$pubbar["Pubbar_Name"] = $row["Pubbar_Name"];
$pubbar["Pubbar_AddressLine1"] = $row["Pubbar_AddressLine1"];
$pubbar["Pubbar_AddressLine2"] = $row["Pubbar_AddressLine2"];
$pubbar["Pubbar_LocationID"] = $row["Pubbar_LocationID"];
$pubbar["Pubbar_Postcode"] = $row["Pubbar_Postcode"];
$pubbar["Pubbar_Latitude"] = $row["Pubbar_Latitude"];
$pubbar["Pubbar_Longitude"] = $row["Pubbar_Longitude"];
$pubbar["Pubbar_TypeID"] = $row["Pubbar_TypeID"];
$pubbar["Pubbar_DateCreated"] = $row["Pubbar_DateCreated"];
$pubbar["Pubbar_DateModified"] = $row["Pubbar_DateModified"];
// push single product into final response array
array_push($response["pubbar"], $pubbar);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No bars found";
// echo no users JSON
echo json_encode($response);
}
This code works on my local WAMP server on my PC
As you can see at the top it connect to another PHP page called "db_connect.php" and the code for that is below:
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();
}
}
Again this work on my local WAMP server database. This also connects to another PHP page called "db_config.php" and the code for that is below:
<?php
/*
* All database connection variables
*/
define('DB_USER', "<USER>"); // db user
define('DB_PASSWORD', "<PASSWORD>"); // db password (mention your db password here)
define('DB_DATABASE', "<DATABASE>"); // database name
define('DB_SERVER', "cust-mysql-X-X"); // db server
?>
As mentioned I have a wamp server setup for testing usage and all this functions as expected through that. However now I wish to put it on my server here, so it is all permanently accessible for my portfolio Android application and the get_all_bars.php page is coming up blank. I've messed around and changed code where I thought it might need changing but unfortunately the page still comes up blank. I have spoke with them before and the config data i.e username, password etc is all correct but I cannot figure out what might be wrong in the rest of this code.

Remove db $conn from MYSQLI query

I'm currently learning mysqli and systematically replacing all of my deprecated queries throughout my script.
I have this query:
<?php
$link = mysqli_connect("host", "user", "pass", "name");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM pins WHERE id='$pinDetails->id'";
$result = mysqli_query($link, $query);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$feature = $row['featured'];
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Which I can echo throughout the page as <?php echo $row['date_featured']; ?>
My question is how do I rework the code to remove the connection? I don't want to keep connecting to the db in every query when I have a general connection include at the top of the page.
Actually you need connection for this page to operate based on your SQL database ,, can you explain more that what do you mean by removing connection
you can use INCLUDE();

Categories