This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I'm trying to make some insert function, but something is wrong, and can find where is the problem. Basically o just set some informations, and this same should be insert in database. The message errors are:
Notice: Undefined variable: conn in /Applications/AMPPS/www/teste/index.php on line 21
Fatal error: Call to a member function query() on a non-object in /Applications/AMPPS/www/teste/index.php on line 21
ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL);
$dbtype = "mysql";
$dbhost = "XXXXXXXXXX";
$dbname = "XXXXXXXXXX";
$dbuser = "XXXXXXXXXX";
$dbpass = "XXXXXXXXXX";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
function Insertdata($table,$field,$data){
$field_values= implode(',',$field);
$data_values=implode(',',$data);
$sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
$result = $conn->query($sql);
}
$table="teste";
$field_values=array("nome","idade","email","cidade");
$data_values=array("Teste","14","teste#yahoo.com","Rio de Janeiro");
$sample = Insertdata($table,$field_values,$data_values);
if($result)
{
echo "inserted";
}
else
{
echo "not inserted";
}
You didn't pass $conn to your function, you'll need to do that in order to have it in scope:
function Insertdata($table, $field, $data, $conn){
$field_values= implode(',',$field);
$data_values=implode(',',$data);
$sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
$result = $conn->query($sql);
}
Related
This question already has answers here:
PHP global in functions
(7 answers)
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 3 years ago.
I was just organizing one of my codes and notice that leaving the connect-mydb.php out of a function, it doesnt work.
I always thought the include would be loaded prior to any of the functions.
connect-mydb.php
<?php
$server = 'localhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydb';
$mysqli = new mysqli($server, $user, $pass, $db);
?>
testdb_out.php (doesnt work)
<?php
include 'connect-mydb.php';
function UpdateDB() {
echo "working\n";
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
testdb_within.php (works)
<?php
function UpdateDB() {
include 'connect-mydb.php';
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
In testdb_out, shouldnt the include be loaded prior to the function? That works in other programming languages.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
Here is the database.php code every time I get this error:
Notice: Undefined variable: dbConn in
C:\xampp\htdocs\couriermanagement\database.php on line 15
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\couriermanagement\database.php on line 15
Warning: mysqli_error() expects exactly 1 parameter, 0 given in
C:\xampp\htdocs\couriermanagement\database.php on line 15
<?php
// database connection config
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'courier_db';
$dbConn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName) or die ('MySQL
connect failed. ' . mysqli_error($dbConn));
//mysqli_select_db($dbConn ,$dbName) or die('Cannot select database. ' .
mysqli_error($dbConn));//
function dbQuery($sql)
{
$result = mysqli_query($dbConn,$sql) or die(mysqli_error());
return $result;
}
function dbAffectedRows()
{
global $dbConn;
return mysqli_affected_rows($dbConn);
}
function dbFetchArray($result, $resultType = MYSQL_NUM) {
return mysqli_fetch_array($result, $resultType);
}
function dbFetchAssoc($result)
{
return mysqli_fetch_assoc($result);
}
function dbFetchRow($result)
{
return mysqli_fetch_row($result);
}
function dbFreeResult($result)
{
return mysqli_free_result($result);
}
function dbNumRows($result)
{
return mysqli_num_rows($result);
}
function dbSelect($dbName)
{
return mysqli_select_db($dbName);
}
function dbInsertId()
{
return mysqli_insert_id();
}
?>
The "link" is missing i think you upgrade from mysql to mysqli
it should look like this:
$dbConn = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($dbConn, "SELECT * FROM test");
read:
http://php.net/manual/en/mysqli.query.php
under Procedural style
You should add
$con=mysqli_connect("hostmane","userename","password","db_name");
before the line
$result = mysqli_query($dbConn,$sql) or die(mysqli_error());
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
This question already has answers here:
MYSQL PHP No Database Selected - Can't Find Error
(2 answers)
Closed 7 years ago.
Here is my php code
<?php
error_reporting(E_ALL);
class ll{
function ll(){
include "sql.php";
}
function getUser($ID) {
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
function setOfflineALL() {
$sql="update users set online=0";
mysql_query($sql);
}
}
$services = new ll();
$services->setOfflineALL(); // THIS WORKS !
$services->getUser(1); // THIS GIVES error: No database selected
?>
and sql.php is:
<?php $hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
?>
sql.php is correct (no error)
setOfflineALL works fine (no error)
getUser raises "no database selected error !", however I do select one with mysql_select_db
I do use php5.4
Any clue ?
I also tried:
function getUser($ID) {
$hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
And still have error:
No database selected
You should try this:
mysql_select_db($database_con1, $con1);
And you should give your database variable to your query too:
mysql_query("query", $con1);
And I strongly advise you not to use mysql but use PDO or mysqli
PDO
Mysqli
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 8 years ago.
I'm getting this error only when I try connect to my localhost, but if i test on my web host, everything is running perfect.
The error i get is pointing on my $query = $dbh->query("SELECT * FROM video");
<?php
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_title;
}
?>
db connection
<?php
$user = "root";
$pass = "";
try {
$dbh = new PDO('mysql:host=localhost;dbname=streaming', $user, $pass);
foreach($dbh->query('SELECT * from video') as $row) {
//print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any tips :)?
Thanks
Looking at the codes you posted, $dbh doesn't make sense since no PDO connection has be initialized:
Second, you are selecting column video_img, then accessing/fetching $r->video_title. This doesn't make sense also:
$dbh = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'username', 'password');
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_img;
}