i am working and new to php i am getting no database selected error;
here is the my code which is dd.php
<?php
include('database.php'); //include of db config file
$pdo = Database::connect();
$per_page = 2; // number of results to show per page
$sql = 'SELECT * FROM customers ORDER BY id DESC';
$result=mysql_query($sql) or die("ERROR".mysql_error()."*****".$sql);
$total_results = mysql_num_rows($sql);
$total_pages = ceil($total_results / $per_page);//total pages we going to have
//-------------if page is setcheck------------------//
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 0;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
fix error in this code one after another i am getting new error like mysql_num_rows() error ODBC#localhost acess denied????
plz help me out??
here is my database.php
<?php
class Database
{
private static $dbName = 'crud_tutorial' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e){
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
problem is due to mysql_* is deprecated replacing with mysqli_ works
Related
consider we have a database with lots of people's details.
I want to filter that result buy available data.
if the table structure is like following,
How to display only results from user with country "India".
It will be possible by accessing object attributes, but I want to add this feature to the following script.
I am not an expert and this script seems to be so difficult for me to understand.
Pagination.php
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
I just want to filter the result.
Full script link https://phppot.com/php/how-to-add-pagination-in-php-with-mysql/
If possible, please add an option to filter the result by an animal name (Common Name), for example "Lion".
Update, here is the working code
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Found solution
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Recently I started to learn PHP and Oracle SQL.
I am trying to fetch list of all rows from the Department table by calling selectAllDepartments function using:
#oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
The above statement executes and returns 2D array $res with correct length. But unfortunately for me empty.
I was trying to echo the $res inside the function by iterating over it the following way:
for ($x = 0; $x < count($res); $x++) {
for ($y = 0; $y < count($res[$x]); $y++) {
echo $res[$x][$y];
echo "<br>";
}
}
here is the class with function:
<?php
class DatabaseHelper
{
const username = '***';
const password = '***';
const con_string = 'lab';
// Since we need only one connection object, it can be stored in a member variable.
// $conn is set in the constructor.
protected $conn;
// Create connection in the constructor
public function __construct()
{
try {
// Create connection
$this->conn = #oci_connect(
DatabaseHelper::username,
DatabaseHelper::password,
DatabaseHelper::con_string
);
//check if the connection object is != null
if (!$this->conn) {
die("DB error: Connection can't be established!");
}
} catch (Exception $e) {
die("DB error: {$e->getMessage()}");
}
}
public function __destruct()
{
// clean up
#oci_close($this->conn);
}
public function selectAllDepartments($deptID, $deptName)
{
if ($deptID && ($deptID != '')) {
$sql = "SELECT * FROM Department WHERE departmentID like '" . $deptID . "'";
} elseif ($deptName && ($deptName != '')) {
$sql = "SELECT * FROM Department WHERE departmentName like " . $deptName . "";
} else {
$sql = "SELECT * FROM Department";
}
$statement = #oci_parse($this->conn, $sql);
#oci_execute($statement);
#oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
echo $sql;
//clean up;
#oci_free_statement($statement);
for ($x = 0; $x < count($res); $x++) {
for ($y = 0; $y < count($res[$x]); $y++) {
echo $res[$x][$y];
echo "<br>";
}
}
return $res;
}
}
I assume that I either parse the data wrongly, or something is wrong with my connection. If so, then how it could be checked?
The problem was that I was wrongly calling the array elements. It should have been done the following way:
foreach ($res as $dept) {
echo $dept['DEPARTMENTID'];
echo $dept['DEPARTMENTNAME'];
echo $dept['NUMBEROFCAGES'];
}
or similarly with ordinary for loop
How to find last inserted id from the following connection php/MySQLi.
I need to find last inserted row id to use that id as a foreign key in another table insertion. I want to use the following code as a database connection.
how to do the transaction, commit, rollback feature in below connection.
<?php
class Database
{
private $db_server = DB_SERVER;
private $db_username = DB_USER;
private $db_pass = DB_PASS;
private $db_name = DB_NAME;
private $con = false;
private $myconn = "";
private $result = array();
private $myQuery = "";
private $numResults = "";
public function connect()
{
if (!$this->con) {
$this->myconn = new mysqli($this->db_server , $this->db_username , $this->db_pass, $this->db_name);
if ($this->myconn->connect_errno > 0) {
array_push($this->result, $this->myconn->connect_error);
return false;
} else {
$this->con = true;
return true;
}
} else {
return true;
}
}
public function sql($sql)
{
$query = $this->myconn->query($sql);
$this->myQuery = $sql;
if ($query) {
$this->numResults = $query->num_rows;
for ($i = 0; $i < $this->numResults; $i++) {
$r = $query->fetch_array();
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
if (!is_int($key[$x])) {
if ($query->num_rows >= 1) {
$this->result[$i][$key[$x]] = $r[$key[$x]];
} else {
$this->result = null;
}
}
}
}
return true;
} else {
array_push($this->result, $this->myconn->error);
return false;
}
}
}
?>
Please help me to find.
Check this. Use:
$this->myconn->insert_id;
I'm moving an older PHP script over to mysqli queries, I'm having trouble with mysqli_real_escape_string in validation code for signups.
PHP message: PHP Notice: Undefined variable: link in
/srv/www/public_html/classes/validation.class.php on line 38
PHP message: PHP Warning: mysqli_real_escape_string() expects
parameter 1 to be mysqli, null given in
/srv/www/public_html/classes/validation.class.php on line 38" while
reading response header from upstream
validation.class.php as follows;
<?php
defined('_VALID') or die('Restricted Access!');
class VValidation
{
public function username($username)
{
if (!preg_match('/^[a-zA-Z0-9_]*$/', $username)) {
return false;
} elseif (preg_match('/^[_]*$/', $username)) {
return false;
}
$users_blocked = array(
'edit',
'prefs',
'blocks',
'delete',
'avatar'
);
if (in_array($username, $users_blocked)) {
return false;
}
return true;
}
public function usernameExists($username) {
global $conn;
$sql = "SELECT UID FROM signup WHERE username = '" . mysqli_real_escape_string($username) . "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function email($email)
{
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
public function emailExists($email, $uid = NULL) {
global $conn;
$sql_add = (isset($uid)) ? " AND UID != " . intval($uid) : NULL;
$sql = "SELECT UID FROM signup WHERE email = '" . mysql_real_escape_string($email) . "'" . $sql_add . " LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function date($month, $day, $year) {
return checkdate($month, $day, $year);
}
public function age($month, $day, $year, $years)
{
$age = mktime(0, 0, 0, $month, $day, $year);
$real_age = mktime(0, 0, 0, date('m'), date('d'), (date('Y') - $years));
if ($age <= $real_age) {
return true;
}
return false;
}
public function zip($code, $country = 'US') {
if (!ctype_digit($code)) {
return false;
}
$length = VString::strlen($code);
switch ($country) {
case 'UK':
case 'CA':
if ($length <> 6) {
return true;
}
default:
if ($length >= 5 && $lenght <= 9) {
return true;
}
}
return false;
}
public function ip($ip)
{
if (!ip2long($ip)) {
return false;
}
}
}
?>
I've wrongly(?) assumed I can include my config to get database details;
<?php
defined('_VALID') or die('Restricted Access!');
require_once $config['BASE_DIR']. '/include/config.php';
and $link mysqli_real_escape_string
$sql = "SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
But this provides the above errors. The include to config.php contains includes to other configs to bring it all together.
<?php
defined('_VALID') or die('Restricted Access!');
require 'config.db.php';
require $config['BASE_DIR']. '/include/dbconn.php';
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$config['db_pass'], $config['db_name']);
if ( !defined('_CONSOLE') ) {
require $config['BASE_DIR']. '/include/sessions.php';
}
disableRegisterGlobals();
... more unreleated functions
config.db.php
<?php
defined('_VALID') or die('Restricted Access!');
$config['db_type'] = 'mysqli';
$config['db_host'] = 'localhost';
$config['db_user'] = 'user1';
$config['db_pass'] = 'abc123';
$config['db_name'] = 'newdatabase';
?>
db.conn.php
<?php
defined('_VALID') or die('Restricted Access!');
$conn = ADONewConnection($config['db_type']);
if ( !$conn->Connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']) ) {
echo 'Could not connect to mysql! Please check your database settings!';
die();
}
$conn->execute("SET NAMES 'utf8'");
?>
Am I going about this the right way? Thanks for any info.
public function usernameExists($username )
{
global $conn, $config;
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$sql="SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
I am trying to do a simple pagination where it'll retrieve data from MySQL and show a previous and next button, no numbers for counting pages, although once the next button is pressed no information are updated, I am not sure if I should use a while or foreach loop.
query
pageClass.php
public function classname
{
$start_page = 0;
$per_page = 8;
if(!isset($_GET['page']))
{
$page = 1;
} else {
$page = $_GET['page'];
}
if($page<=1)
$start_page = 0;
else
$start_page = $page * $per_page - $per_page;
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sth = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$sth->execute(array($start_page, $per_page));
$row = $sth->fetchAll();
return $row;
}
then in a .php file I am displaying it this way, I get the titles but once the buttons are pressed, no other page is opened.
index.php
foreach($latestArticles as $article)
{
$title = $latest['title'];
echo '<div>'.$title.'</div>';
}
$prev = $page - 1;
$next = $page + 1;
echo "
<a href='?page=$prev'>prev</a>
<a href='?page=$next'>next</a>
";
I don't want to put div's in the php classes as it would be a pain to find each class in folders to edit. What am I doing wrong?
First i would recommend you to change your pageClass.php to something more abstract
<?PHP
class pageClass
{
private $db;
private $articlesPerPage = 8;
private $startPage = 0;
public function __construct($db)
{
#TODO check if $db is valid PDO
$this->db = $db;
}
public function setArticlesPerPage($articlesPerPage)
{
$this->articlesPerPage = $articlesPerPage;
}
public function setStartPage($startPage)
{
$this->startPage = $startPage;
}
public function getArticles()
{
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$query = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$queryResult = $query->execute(array($this->startPage, $this->articlesPerPage));
return $queryResult;
}
}
Try to change your index.php to the following
<?PHP
$page = (int)$_GET['page'];
$pageClass = new pageClass($pdo);
if($page > 0)
{
$pageClass->setStartPage($page);
}
$lastestArticles = $pageClass->getArticles();
foreach($lastestArticles as $article)
{
echo '<div>'.$article['title'].'</div>';
}
echo 'prev';
echo 'next';
?>
NOTE: THIS IS EXAMPLE CODE. YOU SHOULD EDIT IT BEFORE COMMITING TO PRODUCTION