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.
Related
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
I have puzzled over this for some time. It is puzzling because a very similar query just a few lines above works fine. I am very new to mysqli, so there may be something very fundamental I am missing.
The connection is set up like this:
Class dbObj{
/* Database connection start */
var $servername = "myserver";
var $username = "myusername";
var $password = "mypassword";
var $dbname = "mydb";
var $conn;
function getConnstring() {
$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$this->conn = $con;
}
return $this->conn;
}
}
Then, in an Ajax processing file:
include_once({the connection file above});
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$NeedsCls = new Needs($connString);
Then, inside a class called "Needs":
protected $conn;
protected $data = array();
function __construct($connString)
{
$this->conn = $connString;
}
function insertNeeds($params)
{
$ExpDate = $params[Expire];
$sql = "INSERT INTO `pNeeds` (PubCode, Title, Description, Keywords, Expire) VALUES('".$_SESSION["PubCode"]."','".$params["Title"]."','".$params["Description"]."','".$params[NeedsTags]."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn, $sql) or die("Error - Failed inserting Needs data");
$Record = $db->insert_id;
$KW = explode(';',$params[NeedsTags]);
$KWCount = count($KW);
for($x=0;$x<$KWCount;$x++)
{
$Keyword = $KW[$x];
$sql = "INSERT INTO `Keywords` (Keyword, PubCode, Table, Record, Expire) VALUES ('".$Keyword."','".$_SESSION["PubCode"]."','pNeeds','".$Record."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn,$sql) or die("Error - Keywords not saved<br />".$mysqli_error());
}
}
The first query works fine. The second fails with the error "Function name must be a string". I've verified the data going into the Ajax code is correct. It doesn't appear that I am missing something stupid. (famous last words) The error message makes no sense to me. Similar posts here on StackOverflow and elsewhere do not seem to pertain in this instance.
It looks like you're just grabbing $params wrong:
$ExpDate = $params[Expire];
$params[NeedsTags];
Should be:
$ExpDate = $params['Expire'];
$params['NeedsTags'];
Edit
You're actual error is from:
$mysqli_error()
Remove the $
Edit
RationalRabbit: To avoid confusing anyone, I should mention that the whole syntax was wrong. Using object oriented mysqli, the error syntax should have been
db->error
OR
mysqli($this->conn)
I am new to the idea of oop php and i am trying to write an irc php.
What I'm trying to do:
I am trying to query my database, get results from my database and put it into an array inside my program.
I tried making a new function to carry out the task and called it in the __construct function.
I have shortened the code but it pretty much looks like this:
Any thoughts and ideas are much appreciated.
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
function __construct()
{
//create new instance of mysql connection
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$this->database_fetch();
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row();
}
}
function main()
{
print_r($array);
}
}
$bot = new IRCBot();
Changes
1) Change if ($mysqli->connect_errno) to if ($conn->connect_errno)
2) Change $array[] = $row(); to $array[] = $row;
3) Add return $array; in function database_fetch()
4) Call database_fetch() function inside main() function instead of constructor.
5) Add $this->conn in mysqli_query() (Thanks #devpro for pointing out.)
Updated Code
<?php
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
public $conn;
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
return $array;
}
function main()
{
$data = $this->database_fetch();
print_r($data);
}
}
Quick Start
Object Oriented Programming in PHP
Classes and Objects
Principles Of Object Oriented Programming in PHP
First of all you need to fix error from your constructor, you can modify as:
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
echo $this->conn->host_info . "\n";
}
Here, you need to replace $mysqli with $conn because your link identifier is $conn not $mysqli
No need to call database_fetch() here.
You need to use $conn as a property.
Now you need to modify database_fetch() method as:
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
Here, you need to pass add first param in mysqli_query() which should be link identifier / database connection.
Second, you need to use return for getting result from this function.
In last, you need to modify your main() method as:
function main()
{
$data = $this->database_fetch();
print_r($data);
}
Here, you need to call database_fetch() method here and than print the data where you need.
This is my code in config.php file:
<?php
$db_username = 'name';
$db_password = 'my password';
$db_name = 'my db';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if ($mysqli->connect_error) {
throw new Exception("Error in Database Connection!");
}
?>
Now I have separate function.php with class commonFunctions
<?php
require_once '../config/config.php';
class commonFunctions {
function doLogin(){
global $mysqli;
$result = $mysqli->query("SELECT * FROM table WHERE itemcolor = 'red'") ;
$row_cnt = $result->num_rows;
return $row_cnt;
}
}
$common=new commonFunctions();
?>
Here I am using global $mysqli; to access $mysqli from config, which may not be a appropriate way to program and using global $mysqli; in every function to access $mysqli looks so bad.
Can you guys pls suggest better and clean way.
Thanks
It depends what programming paradigm you're comfortable with. Personally I like my PHP to be Object Orientated (OO), so i'd put the mysql in a new class called DB or something and then when I want to run the query i'd do $db->query('blabla').
class DB {
private $db;
function __construct() {
$dbConfig = Main::app()->config['db'];
$this->db = new \mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['pass'], $dbConfig['db']);
}
public function query($query, $where = false) {
if (!empty($where)) {
if (strpos(strtolower($where), 'where') > 0)
$query .= ' ' . $where;
else
$query .= ' WHERE ' . $where;
}
$result = $this->db->query($query);
if (!isset($result) || $result === false) {
dd([$query, $this->db->error, $where]);
}
/* will return true on INSERT / UPDATE queries */
if ($result !== true)
return $result->fetch_all(MYSQL_ASSOC);
}
}
Maybe you might just want to create a function in commonFunctions that handled all queries?
function query($query) {
global $mysqli;
return $mysqli->query($query);;
}
PHP:
function generate_uid() {
$uid = mt_rand();
$sql = "SELECT user_id
FROM user_registration";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability = TRUE;
while($row = mysql_fetch_array($result)) {
if($row['user_id'] == $uid) {
$availability = FALSE;
}
}
if($availability == FALSE) {
generate_uid();
}
}
The error
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8
Error:
But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??
$con is not defined in the current variable scope. You can pass the connection to function as a parameter:
function generate_uid($con) {
...
mysql_query($sql, $con);
}
$uid = generate_uid($con);
Or you can use global:
function generate_uid() {
global $con;
...
mysql_query($sql, $con);
}
$uid = generate_uid();
Or, simply leave the connection variable out, and the last opened connection will be used:
function generate_uid() {
...
mysql_query($sql);
}
$uid = generate_uid();
All of those should work.
To learn more about variable scope, check out the PHP manual on the subject at:
http://www.php.net/manual/en/language.variables.scope.php
You are using $con in your function, but $con is not defined in your function scope.
http://php.net/manual/en/language.variables.scope.php
You need to either
a) Pass $con to your function or
b) Set $con as a global
c) Not use $con at all eg.
if (!mysql_query($sql))
however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don't specify a connection it will use the last connection opened.
Inside your function, your MySQL connection doesn't exist. You either need to pass it in, or use the global keyword:
$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function generate_uid()
{
global $con;
$uid = mt_rand();
$sql="SELECT user_id FROM user_registration";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability=TRUE;
while($row = mysql_fetch_array($result))
{
if($row['user_id']==$uid)
{
$availability=FALSE; }
} if($availability==FALSE) { generate_uid(); }
}
while($row = mysql_fetch_array($result))
You can't use that if you plan to use $row as an associative array. Use:
while($row = mysql_fetch_assoc($result))
instead.
EDIT
MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.