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.
Related
I am doing a course on the internet and everything was going well until I had to connect a database. It has not worked for me and I have looked for many solutions but I have 2 days and I do not get anything
Here the database code
<?php
function conectar_bd()
{
$servidor = "127.0.0.1";
$usuario = "jhon28";
$contraseƱa = "Elmenor28519";
$nombrebd = "empresa";
$conexion = mysqli_connect("127.0.0.1", "jhon28", "Elmenor28519");
mysqli_select_db($conexion, $nombrebd);
return $conexion;
}
?>
Here the connection code
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
echo $conexionbd;
mysqli_close ($conexionbd);
?>
Here the error that come to me
Recoverable fatal error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\prueba.php on line 4
Remove echo $conexionbd; or change it to print_r($conexionbd);
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
print_r($conexionbd); //here you are getting object so you can't use echo use print_r instead
mysqli_close ($conexionbd);
?>
based on the docs you wont need select_db, you may insert it on the same function like below.
$link = mysqli_connect($servidor, $usuario, $contraseƱa, $nombrebd);
Therefore, you save one line. Just helping to optimize your code. Refer docs for more information.
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);
i have a php site
in index file include connect to db function :
function connect(){
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("database");
}
and i use this function in everywhere i need connection
for example:
<?php
connect();
$lastnews_sql = mysql_query("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
if(mysql_num_rows($lastnews_sql)) {
while($Result123 = mysql_fetch_object($lastnews_sql)) {
?>
and use this selection:
text; ?>
in end of using :
<?php
}
}
mysql_close();
?>
there are more than 10 connect(); and mysql_close(); in index file
so there are too many connection error in index file
how can i optimize this metod ?
A singleton pattern seems to suit this down to the ground.
class Database
{
private static $instance;
public function getInstance()
{
if(self::$instance == null)
{
// Create a connection to the database.
// NOTE: Use PDO or mysqli. mysql is deprecated.
}
return self::$instance;
}
}
Use
In your classes, instead of calling connect, assuming you're using a PDO object, you could do something like:
$db = Database::getInstance();
$statement = $db->prepare("SELECT * FROM tblName WHERE val = :val");
$statement->bindParam(":val", $value);
$statement->execute();
$result = $statement->fetchAll();
Why this pattern ?
A Singleton pattern has the advantage of only having one instance of itself exist at one time. That means that you will only ever create one connection to the database.
Setting this up
Okay, so the first thing you want to do is to make a new file, let's call it Database.php. Inside Database.php, you want to pretty much write the code that I've written, only do NOT use mysql_*. Have a look at the PDO tutorial that I have provided, on how to connect to a database using a PDO object, and then you put that connection code inside the if statement, so it might look something like:
if(self::$instance == null)
{
self::$instance = new PDO('mssql:host=sqlserver;dbname=database', 'username', 'password');
}
Then, to use it in another class, put a require statement at the top. Something like:
require_once('Database.php');
Finally, look at the code I put in the use section, above. That is how you use it in your class.
Useful links
PDO Tutorial : http://php.net/manual/en/book.pdo.php
Singleton Pattern : http://www.oodesign.com/singleton-pattern.html
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
I'm having some issues using mysqli to execute a script with SELECT,DELETE,INSERT and UPDATE querys. They work when using norm mysql such as mysql_connect but im getting strange results when using mysqli. It works fine with a lot of the SELECT querys in other scripts but when it comes to some admin stuff it messes up.
Its difficult to explain without attaching the whole script.
This is the function for modifying...
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $databaseUsername;
global $databasePassword;
global $databaseDebugMode;
$link = #mysql_connect($databaseServer,$databaseUsername,$databasePassword);
#mysql_select_db($databaseName,$link);
$result = mysql_query($sql,$link);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysql_error()."]";
}
$insertId = mysql_insert_id();
return mysql_affected_rows();
}
and heres what I changed it to for mysqli
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $dbUser_feedadmin;
global $dbUser_feedadmin_pw;
global $databaseDebugMode;
$link = #mysqli_connect($databaseServer,$dbUser_feedadmin,$dbUser_feedadmin_pw,$databaseName);
$result = mysqli_query($link, $sql);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysqli_error()."]";
}
$insertId = mysqli_insert_id();
return mysqli_affected_rows();
}
Does that look right?
It isn't actually producing an error but its not functioning in the same way as when using mysql. any ideas?
Here is the way I normally use Mysqli
$mysqli = new mysqli($myServer, $myUser, $myPass, $myDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
$result = $mysqli->query($query);
while ($row=$result->fetch_assoc()) {
print_r($row);
}
Note: mysqli is a class, $mysqli is the variable that holds the instance of that class, query is a method of that class that returns a result class that has methods of its own.
You are running all statements at once as far as php is concerned, so functions like affected rows or last inserted id will not work as expected.
(Correct me if I'm wrong I haven't been using mysqli for a while.)
some of the mySqli functions needed some tinkering such as including $link