it works... (without the function part) but when I try to use the function on another file I get errors:
<?php
function conectar() {
$s = "localhost";
$u = "root";
$p = "";
$bd = "bd_banco_cesde";
//$conexion = new msqli($s, $u, $p, $bd);
//$conexion = #new msqli($s, $u, $p, $bd);
$conexion = mysqli_connect($s, $u, $p, $bd);
if ($conexion->connect_errno) {
echo "No conectado";
} else {
echo "Conectado... uf";
}
}
include('php_conectado.php');
$con = conectar();
echo "$con";
?>
Errors
Your function need some changes:
echo is not proper solution use die:
return connection because you need to use from that in the next codes.
print_r($con); connection to see its resault
$conexion=mysqli_connect($s,$u,$p,$bd);
if($conexion->connect_errno)
{
die("No conectado");
}
else
{
return $conexion;
}
return false;
}
//
include(php_conectado.php);
$con=conectar();
print_r($con);
Also you can use return false; instead of die("No conectado");, and in this case when $con is false there is no connection
Also you need to have $conexion for execution next queries and without that it is not possible to run query in this connection
Related
I am pretty new to PHP, I have referred some examples and made a code for getting data from database. but if the database is not found I am getting a text response , Can anyone suggest how to get a proper JSON response back if no database found or misconfigured
This is my $http.get method
$http.get('client/php/popData.php')
.success(function(data) {
$scope.blogs = data;
})
.error(function(err) {
$log.error(err);
})
popdata.php for getting data from database
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$db = new DB();
$data = $db->qryFire();
echo json_encode($data);
?>
This is my config.php
<?php
define("__HOST__", "localhost");
define("__USER__", "username");
define("__PASS__", "password");
define("__BASE__", "databasename");
class DB {
private $con = false;
private $data = array();
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
die("DB connection failed:" . mysqli_connect_error());
}
}
public function qryPop() {
$sql = "SELECT * FROM `base` ORDER BY `id` DESC";
$qry = $this->con->query($sql);
if($qry->num_rows > 0) {
while($row = $qry->fetch_object()) {
$this->data[] = $row;
}
} else {
$this->data[] = null;
}
$this->con->close();
}
public function qryFire($sql=null) {
if($sql == null) {
$this->qryPop();
} else {
$this->con->query($sql);
$this->qryPop();
}
// $this->con->close();
return $this->data;
}
}
?>
Use Exceptions:
Change your class DB like this:
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
Then change your popdata.php like
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
try {
$db = new DB();
$data = $db->qryFire();
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
exit();
}
echo json_encode($data);
This way you will get error response in JSON for any Exception thrown while constructing the DB class and while executing DB::qryFire
if you want to catch your warnings you can try modifying your DB class like the below:
public function __construct() {
ob_start();
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
$warning = ob_clean();
if ($warning) {
throw new Exception($warning);
}
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
You can also turn off your warnings and notices by adding
error_reporting(E_ERROR);
on the top of your file
replace the line die("DB connection failed:" . mysqli_connect_error()); in DB class __construct function with
die( json_encode( array('status' => 'error') ) );
when ever the app will fail to connect to the data base it will give
{"status": "error"}
i did not checked this. but i hope it will work
btw it's my 1st answer on stackoverflow. i'm sorry for my mistakes. correct them
I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.
I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?
I know how to display data without using class, but i have been asked to use mysql class instead. It seems that i have to initiate the class and just use the written functions, but whatever i try to display - it doesn't work. All i am getting is "Resource id #14", which means that everything should be good with the connection. Please help!
This is a part of the MySQL class:
class SQL //MySQL
{
var $link_id;
var $query_result;
var $num_queries = 0;
function connect($db_host, $db_username, $db_password, $db_name = '', $use_names = '', $pconnect = false, $newlink = true) {
if ($pconnect) $this->link_id = #mysql_pconnect($db_host, $db_username, $db_password);
else $this->link_id = #mysql_connect($db_host, $db_username, $db_password, $newlink);
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
if ($this->link_id){
if($db_name){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
}
} else die(mysql_error());// = "Can't connect to mysql server";
}
function db($db_name) {
if ($this->link_id){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
} else die(mysql_error());// = "Can't connect to database";
}
function query($sql){
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result){
++$this->num_queries;
return $this->query_result;
} else {
$error = "
<pre>
QUERY: \n {$sql} \n\n
ERROR: <span style=\"color:red\">" . mysql_error() . " </span>
</pre>
";
die($error);
}
}
function result($query_id = 0, $row = 0, $field = NULL){
return ($query_id) ? #mysql_result($query_id, $row, $field) : false;
}
function fetch_row($query_id = 0){
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
function fetch_array($query_id = 0){
return ($query_id) ? #mysql_fetch_array($query_id) : false;
}
function fetch_assoc($query_id = 0){
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
function num_rows($query_id = 0){
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
....
and my php code:
<?php
require_once('C:/wamp/www/smarty-3.1.21/libs/Smarty.class.php');
include('C:/wamp/www/smarty-3.1.21/libs/Mysql.class.php');
$smarty = new Smarty();
$smarty->enableSecurity();
$smarty->setTemplateDir('C:\wamp\www\forum\templates');
$smarty->setCompileDir('C:\wamp\www\forum\templates_c');
$smarty->setConfigDir('C:\wamp\www\forum\configs');
$smarty->setCacheDir('C:\wamp\www\forum\cache');
$db = new SQL();
$db->connect('localhost','root','','job', '', false, true);
$db->db('job');
$sql = "SELECT * FROM job";
$db->query($sql);
$output = $db->query_result;
$result = $db->fetch_row();
$smarty->assign('rez', $result);
$smarty->assign('output', $output);
$smarty->display('index.tpl');
?>
I am wondering how $link can be undefined. It is a global inside class cdb.php and is set when the mysql connect is called. If it were undefined, when mysql connect was called, it would die because I have coded it this way.
<html>
<head>
</head>
<body>
<?php
function justGetCSNumbers($input)
{
$input = preg_replace('/[\D]/',"",$input);
$sp = preg_split("/,/",$input);
$numbs = preg_grep('/^(\d+)(,\d+)*$/',$sp);
$csv = implode(",",$numbs);
#echo $csv;
return $csv;
}
function queryDB($cleaned)
{
$split = preg_split('/,/',$cleaned);
$resAy = array();
for($i=0;$i<count($split);$i++)
{
if((strlen($split[$i])>5)&&(strlen($split[$i])<10))
{
$resAy[$i] = "uid='$split[$i]'";
}
}
if(count($resAy)>0)
{
$q = 'SELECT * FROM userbase WHERE '.$resAy[0];#.$whereclause;
echo '<br/> query: '.$q.'<br/>';
connectDB();
return mysql_query($q,$link) or die("Couldn't complete query ".mysql_error($link));
}
}
function find(){
$p = $_POST['userToQuery'];
if(isset($p))
{
$csv = justGetCSNumbers($p);
$found= queryDB($csv);
}
}
include('cdb.php');
find();
?>
Sorry for the poorly formatted code, using vi.
My apache2 error log shows that the variable $link is undefined when i use it here, even after calling connectDB(); which is the code that does a mysql_connect and therefore sets up the link.
'mysql_error() expects parameter 1 to be resource, null given'
I refactored my code so the link would be defined (this version), but somehow I am having trouble.
[EDIT]
Here is the cdb.php class:
<?php
function connectDB()
{
global $link;
$uname = 'site123';
$pass = 'abc123';
$loc = "localhost";
$link = mysql_connect($loc, $uname, $pass) or die("Couldn't connect to the DB");
$dbname = 'jagrail';
$db = mysql_select_db($dbname,$link);
if(!$db)
{die("Failed to select db");}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
#return $link;
}
?>
EDIT:
Add:
global $link;
to the top of the queryDB() function, so that it knows $link is a global variable, rather than just a local.