I have a class like this:
<?php
class DataConnection {
private $hostName = "localhost";
private $username = "root";
private $password = "";
private $dbName = "test";
private $link = "";
public function __construct() {
}
private function connect() {
$this->link = mysql_connect($this->hostName, $this->username, $this->password)
or die ("Could not connect to the database");
mysql_select_db($this->dbName, $this->link) or die("Could not select database");
}
// lay kieu du lieu cua record trong table
public function getDataTypeTable($tableName) {
$this->connect();// ERROR HERE
$query = "SELECT * FROM {$tableName}";
$result = mysql_query($query);
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
//var_dump($results);
//mysql_free_result($results);
}
public function __destruct() {
mysql_close($this->link);
}
}
?>
I get an error "Fatal error: Using $this when not in object context in C:\xampp\htdocs\demo\test\DataConnection.php on line 44", it means that there is something wrong in connect function. How can I fix it? Thanks for watching!
Related
So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.
From the code below, i need help on how I can print something like this:
echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
This is the code I need to be modified :
<?php
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
}
echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Just like you normally would print results of SELECT query. Although here it seems there's an ajax call invovled.
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
$result = null;
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
$result = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
$result = $products;
}
// echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
$html = "";
foreach ($result as $row) {
$html .= "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
}
// return as HTML (won't work in ajax)
echo $html;
// or for ajax:
echo json_encode($html, JSON_PRETTY_PRINT) . "\n";
// or
echo json_encode(["html" => $html], JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
I'm trying to get value from memcache.
value of $dataOld[$i] is null when I'm trying to read that in if statement outside of if block it contains right value.
This is my code.
My code is for get and send data .
any help will be much appreciated.
<?php
/**
* Created by PhpStorm.
* User: PC1
* Date: 9/18/2018
* Time: 11:57 AM
*/
include 'config.php';
include 'BefrestAuth.php';
include 'Publisher.php';
$memcahe = new Memcache();
$memcahe->connect("localhost", 11211);
$dataNew = json_decode($memcahe->get('keyNew'));
$memcahe->set('keyOld', json_encode($dataNew));
while (true) {
$dataNew = json_decode($memcahe->get('keyNew'));
$dataOld = json_decode($memcahe->get('keyOld'));
if (!$dataNew[0]->price) {
continue;
} else {
$str = "";
$taskolu = array();
for ($i = 0; $i < count($dataNew); $i++) {
if ((int)$dataNew[$i]->price > (int)$dataOld[$i]->price) {
echo "\n".$dataNew[$i]->price."/////".json_encode($dataOld[$i])."\n";
$str .= "name:" . $dataNew[$i]->name . " type:" . $dataNew[$i]->type . " price:" . $dataNew[$i]->price."\n";
array_push($taskolu, $dataNew[$i]);
}
if ((int)$dataOld->price > (int)$dataNew[$i]->price) {
$str .= "name:" . $dataNew[$i]->name . " type:" . $dataNew[$i]->type . " price:" . $dataNew[$i]->price."\n";
array_push($taskolu, $dataNew[$i]);
}
}
if (!empty($str)) {
$dbca = connection();
$dbca->set_charset("utf8");
$rate = "SELECT u.user_chid FROM users u";
$result = $dbca->prepare($rate);
$result->execute();
$res = $result->get_result();
while ($obj = $res->fetch_object()) {
$auth = (string)BefrestAuth::generatePublishAuth($obj->user_chid);
Publisher::publish(11812, $obj->user_chid, $auth, json_encode(array("messages" => $taskolu)));
echo "\n";
}
}
$memcahe->delete('keyOld');
$data=json_encode($dataNew);
$memcahe->set('keyOld', $data);
$dataOld = json_decode($memcahe->get('keyOld'));
}
}
I'm trying to read from mysql with php and with oop.How can use from propeties?
This is my class and search function for reading from the database:
<?php
require_once('dbconfig.php');
class Film {
public $name;
public $year;
public $country;
public $director;
private $conn;
public function __construct() {
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql) {
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function search($name,$year,$country,$director) {
try {
$stmt = $this->conn->prepare("SELECT * FROM table where name='$name' or year='$year' or country='$country' or director='$director'");
$stmt->execute();
$num_rows = $stmt->rowCount();
if ($num_rows > 0) {
echo "</br>".$num_rows." film is found. </br>";
echo "</br><table><tr><th>Name</th><th>Year</th><th>Country</th><th>durationMinutes</th><th>Director</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['year'] . "</td><td>" . $row['country'] . "</td><td>" . $row['durationMinutes'] . "</td><td>" . $row['director'] . "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found !";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
I want search() is based on the object and properties.
How to change my code?
Did you mean you want to call that function?
just put this code wherever you wanna place it e.g in index.php.
$film->search($name,$year,$country,$director);
but you have to initial class film in your connection file like this
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$database="database";
try {
$con = new PDO ("mysql:host={$host}; dbname={$database}", $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
}
catch (PDOEXception $e) {
echo $e->getMessage();
}
include_once 'class_film.php';
$film= new Film($con);
This question already has answers here:
Using a .php file to generate a MySQL dump
(13 answers)
Closed 7 years ago.
How can I take backup of all tables of a database from ftp without using phpmyadmin and get the backup as a .sql file ??
Use shell_exe() to create the backup via PHP.
<?php
$dbuser = ''; // database user
$dbpass = ''; // database password
$dbhost = ''; // database host
$dbname = ''; // database name
$create = shell_exec("mysqldump --user=$dbuser --password=$dbpass --host=$dbhost $dbname> mysql_dumb.sql");
// header('Location: mysql_dumb.sql'); // you can optionally download it but secure access to the file before doing this
?>
This script would do whatever you need.
MySQL connections need to be improved though, but works fine.
<?php
// Report all errors
error_reporting(E_ALL);
/**
* Define database parameters here
*/
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_NAME", '');
define("DB_HOST", '');
define("OUTPUT_DIR", '');
define("TABLES", '*');
/**
* Instantiate Backup_Database and perform backup
*/
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "<br /><br /><br />Backup result: " . $status;
/**
* The Backup_Database class
*/
class Backup_Database
{
/**
* Host where database is located
*/
var $host = '';
/**
* Username used to connect to database
*/
var $username = '';
/**
* Password used to connect to database
*/
var $passwd = '';
/**
* Database to backup
*/
var $dbName = '';
/**
* Database charset
*/
var $charset = '';
/**
* Constructor initializes database
*/
function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8')
{
$this->host = $host;
$this->username = $username;
$this->passwd = $passwd;
$this->dbName = $dbName;
$this->charset = $charset;
$this->initializeDatabase();
}
protected function initializeDatabase()
{
$conn = mysql_connect($this->host, $this->username, $this->passwd);
mysql_select_db($this->dbName, $conn);
if (!mysql_set_charset($this->charset, $conn)) {
mysql_query('SET NAMES ' . $this->charset);
}
}
/**
* Backup the whole database or just some tables
* Use '*' for whole database or 'table1 table2 table3...'
* #param string $tables
*/
public function backupTables($tables = '*', $outputDir = '.')
{
try {
/**
* Tables to export
*/
if ($tables == '*') {
$tables = array();
$result = mysql_query('SHOW TABLES');
while ($row = mysql_fetch_row($result)) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql .= 'USE ' . $this->dbName . ";\n\n";
/**
* Iterate tables
*/
foreach ($tables as $table) {
echo "Backing up " . $table . " table...";
$result = mysql_query('SELECT * FROM ' . $table);
$numFields = mysql_num_fields($result);
$sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
$sql .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++) {
while ($row = mysql_fetch_row($result)) {
$sql .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("[^\r]\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$sql .= '"' . $row[$j] . '"';
} else {
$sql .= '""';
}
if ($j < ($numFields - 1)) {
$sql .= ',';
}
}
$sql .= ");\n";
}
}
$sql .= "\n\n\n";
echo " OK" . "<br />";
}
}
catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/**
* Save SQL to file
* #param string $sql
*/
protected function saveFile(&$sql, $outputDir = '.')
{
if (!$sql)
return false;
try {
$handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
fwrite($handle, $sql);
fclose($handle);
}
catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return true;
}
}
Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }