after php code row 1 and 2, I got a notice and error message.
Notice: Undefined variable: dbc in ...
Warning: mysqli_get_host_info()
expects parameter 1 to be mysqli, null given in ...
connectdb();
echo mysqli_get_host_info($dbc);
Can you help me please to solve my notice & warning? How can I make $dbc defined also for outher functions? I am working with error level -1 by the time being. please don't tell not to display the notices as a solution. Unfortunately, I can't understand the custom function variable passage issues. thanks.
function connectdb()
{
$dbc = mysqli_connect (db_host, db_user, db_password, db_name);
if (!$dbc)
{
$txt = mysqli_connect_errno().mysqli_connect_error();
db_connect_error_mail($txt);
unset ($txt);
die('error message.');
}
else
{
return $dbc;
}
}
You aren't assigning the return value of connectdb() method anywhere. You want:
$connection = connectdb();
echo mysqli_get_host_info($connection);
For clarity I have used a different variable name as the one you use in your function, because they are different variables, as they are defined in different scopes.
Think, you are returning $dbc, from the function, but you are not assigning the return value of the connectdb() function in line 1. How will the compiler know that you saved the return value in $dbc?
$dbc = connectdb();
This will fix your error.
Related
This question already has answers here:
What does the variable $this mean in PHP?
(11 answers)
Closed 3 years ago.
I have this code:
class database{
var $conn;
function connect($server,$host_username,$host_password,$host_database){
$server = 'localhost';
$host_username = 'root';
$host_password = '';
$host_database = 'e-vent system db';
$conn= new mysqli($server,$host_username,$host_password,$host_database);
if ($conn->connect_error){
die("db connection error:". $conn->connect_error);
}
}
function read_db($table,$condition){
$read="SELECT * FROM ".$table." ".$condition;
$read_result=$conn->query($read);
if(!$read_result){
echo "select error:". mysqli_error($conn);
}
return $result;
}
}
And I get this error:
Notice: Undefined variable: conn in C:\xampp\htdocs\E-vent\database.php on line 19
How can I make the $conn variable visible to the read_db function?
Change this line:
if ($conn->connect_error){
to
if ($this->conn->connect_error){
means replace all:
$conn->query
to
$this->conn->query
Explanation: If you want to use a variable in the entire class scope then you have to use the class variable instead of local (function) scope variable. In this line:
$conn->connect_error
the $conn is a local variable whose scope is limited to the function only, but when you use $this->conn, it means you are referring to the class variable which is accessible in all the member functions of the class.
And put all the content of connect function in the class constructor so that this connection is initialized at the time of class initialization. (Thanks #Magnus for pointing this)
Have a look on the variable scope, it will help you to understand the concept.
You are using class variable into a function, it's basic rule of oops that to use class variable we must access it using object. so class variable can be used under same class using $this.
so your code must be:
$this->$conn->connect_error
Instead of
$conn->connect_error
You need to make the connection object a property of the class, using $this - specifically, $this->conn. Assign your connection-object to that property. You then need to reference $this->conn everywhere else within that class, instead of using $conn.
class database {
public $conn;
public function connect($server, $host_username, $host_password, $host_database)
{
$server = 'localhost';
$host_username = 'root';
$host_password = '';
$host_database = 'e-vent system db';
$this->conn = new mysqli($server, $host_username, $host_password, $host_database);
if ($this->conn->connect_error) {
die("db connection error:". $this->conn->connect_error);
}
}
public function read_db($table, $condition)
{
$read = "SELECT * FROM ".$table." ".$condition;
$read_result = $this->conn->query($read);
if (!$read_result) {
echo "select error:". mysqli_error($this->conn);
}
return $result;
}
}
That being said, a couple of things to note,
You are not using parameterized queries, and are injecting variables directly into the query -- this is not secure, and you should use a prepared statement with placeholders.
The connect() method takes in all the arguments, but you still overwrite them in the function. Alternatives are to remove the arguments, remove the hard-coded values, or use the hard-coded values if the argument is empty.
You should not return errors to the user while in production. During development, this is fine - but in production, hide them, log them and display something generic to the user instead (like a 500 page, or some other error page).
You should specify if your properties and methods are public, protected, static or private.
Better to use public access modifier without using var. What does PHP keyword 'var' do?.
Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.
And also The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.
PHP variables - http://php.net/manual/en/language.variables.variable.php
Need to change as follows
class database{
public $conn
And here
$this->conn= new mysqli($server,$host_username,$host_password,$host_database);
And here
if ($this->conn->connect_error){
die("db connection error:". $this->conn->connect_error);
}
And here as well
$read_result=$this->conn->query($read);
.../general.php on line 10
Hello, this is my error, but only occurs when I upload my web to a host, in the localhost run well.
the (return mysqli_real_esc..)line is the "line 10".
$conncet = mysqli_connect('xxx','xxx','xxx','xxx');
function array_sanitize(&$datos) {
global $connect;
$datos = mysqli_real_escape_string($connect,$datos);
}
thanks for your time!!
i think you have typo in your variable, please check your $connect => $conncet variable
$conncet = mysqli_connect('xxx','xxx','xxx','xxx');
function array_sanitize(&$datos) {
global $connect;
$datos = mysqli_real_escape_string($connect,$datos);
}
You misspelt connect in your initialization. You spelt it conncet. The only reason I can think for that running well on localhost is if errors are set not to show.
first off there is a spelling error on your first line "$conncet" should be $connect
I suspect that your credentials(username & password) is wrong on the web. Find your username and password for the online database.
I get "Notice: Undefined variable: con in C:\wamp\www\Game\functions.php on line 8" when trying to use the function, here's the code.
function protect($string) {
return mysqli_real_escape_string($con,strip_tags(addslashes($string)));
}
I use the $con for my queries and it's fine so I thought that was what was for this mysqli part?
This is for registration, I have some registration that is working but I can't use that, here's a confirmed working line
$res=mysqli_query($con,$sql);
Any ideas?
$con doesn't exist in the function protect(), so you either need to make $con global:
global $con = mysqli_connect();
or you need to pass $con as an argument:
function protect($string, $con) {
return mysqli_real_escape_string($con,strip_tags(addslashes($string)));
}
ANSWER FROM MIHAI
mysqli_real_escape_string needs a connection BEFORE it can function,use global $con; as the first line in your function. – Mihai
hoping someone can help me, I am having the following error, looked online and tried a load of things but can't seem to figure it out, error:
Fatal error: Call to undefined method mysqli::mysqli_fetch_all() in C:\xampp\htdocs\cyberglide\core-class.php on line 38
heres my code:
<?php
class Core {
function db_connect() {
global $db_username;
global $db_password;
global $db_host;
global $db_database;
static $conn;
$conn = new mysqli($db_host, $db_username, $db_password, $db_database);
if ($conn->connect_error) {
return '<h1>'."Opps there seems to be a problem!".'</h1>'.'<p>'."Your Config file is not setup correctly.".'</p>';
}
return $conn;
}
function db_content() {
//this requires a get, update and delete sections, before its complete
$conn = $this->db_connect();
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM content";
// Escape Query
$query = $conn->real_escape_string($query);
// Execute Query
if($result = $conn->query($query)){
// Cycle through results
while($row = $conn->mysqli_fetch_all()){
//echo $row->column;
}
}
}
}
$core = new Core();
?>
I am trying to create a db_connect function, which I want to be able to call anywhere on the site that needs a database connection, I am trying to call that function on a function within the same class, I want it to grab and display the results from the database. I am running PHP 5.4.7, I am calling the database on a blank php file which includes a require to include the class file, then using this at the moment $core->db_content(); to test the function. I am building this application from scratch, running from MySQLi guides (not used MySQLi before, used to use normal MySQL query's) so if I am doing anything wrong please let me know, thanks everyone.
mysqli_fetch_all is a method of a mysqli_result, not mysqli.
So presumably it should be $result->fetch_all()
References:
http://php.net/manual/en/mysqli-result.fetch-all.php
Important: keep in mind mysqli_result::fetch_all returns the whole result set not a row as you assume in your code
There are three problems I see here.
while($row = $conn->mysqli_fetch_all()){
The method name is fetch_all() when used in the OOP way.
fetch_all() should be used with the $result object
fetch_all() is only available when the mysqlnd driver is installed - it frequently is not.
Reference
Only $result has that method. If you want to use it in a while loop use fetch_assoc(). fetch_all() returns an associative array with all the data already.
while($row = $result->fetch_assoc()){
}
thanks all, its working fine now, i had it as while($row = $conn->fetch_assoc()){
} before and changed to what i put above, but dident see it should of been $result instead of $conn, thanks for pointing that out.
I have this php file. The lines marked as bold are showing up the error :"mysql_query() expecets parameter 2 to be a resources. Well, the similar syntax on the line on which I have commented 'No error??' is working just fine.
function checkAnswer($answerEntered,$quesId)
{
//This functions checks whether answer to question having ques_id = $quesId is satisfied by $answerEntered or not
$sql2="SELECT keywords FROM quiz1 WHERE ques_id=$quesId";
**$result2=mysql_query($sql2,$conn);**
$keywords=explode(mysql_result($result2,0));
$matches=false;
foreach($keywords as $currentKeyword)
{
if(strcasecmp($currentKeyword,$answerEntered)==0)
{
$matches=true;
}
}
return $matches;
}
$sql="SELECT answers FROM user_info WHERE user_id = $_SESSION[user_id]";
$result=mysql_query($sql,$conn); // No error??
$answerText=mysql_result($result,0);
//Retrieve answers entered by the user
$answerText=str_replace('<','',$answerText);
$answerText=str_replace('>',',',$answerText);
$answerText=substr($answerText,0,(strlen($answerText)-1));
$answers=explode(",",$answerText);
//Get the questions that have been assigned to the user.
$sql1="SELECT questions FROM user_info WHERE user_id = $_SESSION[user_id]";
**$result1=mysql_query($sql1,$conn);**
$quesIdList=mysql_result($result1,0);
$quesIdList=substr($quesIdList,0,(strlen($quesIdList)-1));
$quesIdArray=explode(",",$quesIdList);
$reportCard="";
$i=0;
foreach($quesIdArray as $currentQuesId)
{
$answerEnteredByUser=$answers[$i];
if(checkAnswer($answerEnteredByUser,$currentQuesId))
{
$reportCard=$reportCard+"1";
}
else
{
$reportCard=$reportCard+"0";
}
$i++;
}
echo $reportCard;
?>
Here is the file connect.php. It is working just fine for other PHP documents.
<?php
$conn= mysql_connect("localhost","root","password");
mysql_select_db("quiz",$conn);
?>
$result2=mysql_query($sql2,$conn);
$conn is not defined in the scope of your function (even if you're including the connect.php file before that.
although you can use the suggestion to make $conn global, it's usually better practice to not make something global just for the sake of globalizing it.
i would instead pass $conn to the function as a parameter. this way, you can reuse the same function you wrote with different connections.
$conn isn't declared as a global so the function cannot access it, as it is not defined within it.
Either simply add
global $conn;
To the top of the function to allow it to access the $conn.
Or you can remove $conn from the mysql_query() statement. By default it will use the current connection (as mentioned in the comments below).
Where do you set $conn? It doesn't look like you set a connection within that function