MySQL Not Showing Data - php

I have a basic script below to show values from a database; it has worked for years now, but suddenly I'm getting empty results with no errors.
I'm thinking maybe the way to query data has changed? My script is below (note the db login details are correct, and connection is fine):
<?php
// Get Database Login
define("DB", dirname(dirname(__FILE__)) . "/");
require(DB . "../../ipSecure/db.ipSecure.php");
// End
// Connect To Database
$conn = mysql_connect($ipSecure_dbhost, $ipSecure_dbuser, $ipSecure_dbpass) or die ("Error Connecting to MYSQL");
mysql_select_db($ipSecure_dbname);
// End
// Find ipSecure Status
$ipSlicense = mysql_query("SELECT * FROM `license` WHERE `c_id` = 'inkgear-josh'");
$ipSlicense_result = mysql_fetch_assoc($ipSlicense);
// Show ipSecure Status
echo $ipSlicense_result["c_id"];
// End
?>

You can try this:
<?php
// Get Database Login
define("DB", dirname(dirname(__FILE__)) . "/");
require(DB . "../../ipSecure/db.ipSecure.php");
// End
// Connect To Database
/* ESTABLISH CONNECTION */
$conn=mysqli_connect($ipSecure_dbhost,$ipSecure_dbuser,$ipSecure_dbpass,$ipSecure_dbname);
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
// End
// Find ipSecure Status
$ipSlicense = mysqli_query($conn,"SELECT * FROM `license`");
while ($ipSlicense_result = mysqli_fetch_array($ipSlicense)){
// Show ipSecure Status
echo $ipSlicense_result['c_id'];
echo " - ".$ipSlicense_result['company_name']."; Status: ".$ipSlicense_result['status']."<br>";
// End
}
?>
I've convert your code to MySQLi at least, instead of deprecated MySQL.

Related

What I'm doing wrong? "cronjob"

I have MySQL database, it contain a table with a column called "downloads"
I want to update this column to 0 every 24h, but it seems my code doesn't work!
I have folder on the server named cron.
Inside it there is two files, one to connect to the database, and the other contain the php code to reset the column downloads to 0
This is my connection code:
<?php
$link = mysqli_connect("localhost", "test", "root", "test1");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
?>
And my php code that I want to use it in cronjob is this one:
<?php
require_once('/home/cron/connect.php'); // connect to db
$mysqli = ("update users set downloads = 0");
$mysqli->close();
?>
I fired the file directly from the browser but it doesn't reset the column downloads to zero! what I'm doing wrong?
Note: of course there is .htaccess file to protect direct access to the connection file
EDIT: There is no error at connection if I run the code of connection, but the second code from cronjob doesn't work!
You do not need $mysqli->close(); at all. Your connection object is called $link. The second line should be:
$link->query("update users set downloads = 0");
You should probably also check if it executed properly and if not do something about it.
Your full code in second file could look like this (assuming the connection is successful):
<?php
require_once('/home/cron/connect.php'); // connect to db
if( $link->query("update users set downloads = 0") ){
// succesful
} else {
// fail
}

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 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.

Query running in PHPmyadmin but not through PHP

I am trying to run a query from PHP which is not running but I can run the query from within phpMyAdmin
here is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].' ?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
$id_to_delete = $_GET['yesdelete'];
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_GET['yesdelete']);
//$sql=mysql_query("SELECT id FROM admin WHERE username = '$manager' AND password='$password' LIMIT 1 ");
$sql = mysql_query( $conn ,"DELETE FROM products WHERE id=`$id_to_delete` LIMIT 1 ") or (mysql_error());
//echo 'The data at number ' . $id_to_delete . ' Deleted Sucessfully';
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
// header("location:inventory_list.php");
//exit();
}
?>
I am new to PHP so your help is sought, i am able to connect to to database at another instance the code of which is following
<?php
//checking the user
ob_start();
session_start();
if (!isset($_SESSION["manager"])){
header ("location:admin_login.php");
exit();
}
//be sure to check if this manager SESSION value is in the database
$managerID=preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
$password=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
//runMYSQL query to assertain that this is manager
//Connect to mysql database
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password'LIMIT 1");
// make sure person exists in database
$existCount=mysql_num_rows($sql);
if ($existCount== 0)
{
echo "your data do not match our records";
exit();
}
?>
The code in connect_to_my_sql.php is as follows
<?php
/*
1: "die()" will exit the script and show an error statement if something goes wrong with the "connect" or "select" functions.
2: A "mysql_connect()" error usually means your username/password are wrong
3: A "mysql_select_db()" error usually means that the database does not exist
*/
// Place db host name Sometimes "localhost" but
// sometimes looks like this:>> ???mysql??.someserver.net
$db_host = "localhost";
//Place the username for the MySQL database here
$db_username = "storeuser";
//Place the password for the MySQL database here
$db_pass = "rajjar";
//Place the name for the MySQL database here
$db_name="mystore";
// Run the actual connection here
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
//mysql_select_db("$db_name") or die ("no database");
?>

Header, logic and database

I am having an issue with my header location. I am new to php and I am unable to redirect to my index page after this separate php file is run. In addition my function is unable to tell whether the contents of a text box is blank or equal to the default value of "<>".
Thank you
<?php
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
{
// the form was submitted
//remove hacker HTML
$email2=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email2'";
$result=mysql_query($sql2);
//Direct back to homepage
echo "heloooo";
header('location:/index.php');
}
else
{
header('location:/index.php');
}
}
else
{
header('Location:http://www.google.com');
`enter code here`}
?>
EDIT
After making the changes suggested my error log is as follows
Notice: Use of undefined constant db_selected - assumed 'db_selected' in /home/clubbtpk/public_html/connectionFile.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /home/clubbtpk/public_html/connectionFile.php:15) in /home/clubbtpk/public_html/addEmail.php on line 28
The code in the connection file is:
<?php
$host="localhost";
$username="username";
$password ="password";
// Create connection to mysql server
$con=mysql_connect("$host","$username","$password");
// Check connection
if (!$con)
{
die ("Failed to connect to MySQL: " . mysql_error());
}
// Select database
$db_selected = mysql_select_db("DB", $con);
if(!db_selected)
{
die ("Cannot connect : " . mysql_error());
}
?>
EDIT 2
Resolved first error by changing
if(!db_selected)
to
if(!$db_selected)
RESOLVED
Added the following line of code to my index.php file:
<?php
if(isset($_REQUEST["emailAdd"])){
include("addEmail.php");
}
?>
Then changed the action of the form to "" so that it reloads the current page:
<form name="emailAddr" method="post" action="">
You must not output anything before your redirect.
So this is not allowed:
echo "heloooo";
header('location:/index.php');
EDIT: You should definitely enable error_reporting on your script. I found another error in your query:
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
should be
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
Furthermore you should not use the mysql_* functions anymore but upgrade to mysqli_* functions. And always check the inputted data before inserting them into sql-queries.
EDIT2: Add this at the beginning of your script:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
EDIT3:
You have to change this line too:
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
Should be:
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>")
If you would turn error_reporting on you would see it yourself.

Categories