I am trying to connect to mysql via php using this line
# $db = new mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
I am not getting any response, no error message, nothing. I even added an echo'hi';
after the first line of code and it doesn't show up. When I added echo'hi'; before the first line hi prints out.
Any tips?
Get rid of the new instead do:
$db = mysqli_connect(...
or use new to create a mysqli object
$db = new mysqli(...
In the first case $db is assigned the return value of a function. The mysqli_connect function passes back the object created internal to the function. In the second case $db is being created through the new keyword as the result of the "new mysqli(..." expression.
First of all, remove the # before function calls. # is to suppress any errors from coming up.
Second, remove the new keyword. That's for instantiating a new class, not calling a function.
$db = #mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
mysqli_connect is not an object it is function
EDIT:
remove #, make sure your error_reporting( E_ALL );
$db = mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
"Call to undefined function mysqli_connect()" - do you have mysqli module on ? - Yes in php.ini file.
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:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.
I have create a test function to store user message in database and m using mysqli_connect for database connection. But when i create every new function i need to open mysqli connection in every new function. Its frustrated for me.
Have look at code
function abb() { $db = new mysqli("localhost","root","","homeland");
$dat = "insert into tbl_queryform(user_name,user_email,user_query)values('vijender Singh','vv#gmail.com','dds')";
$dat2 = mysqli_query($db, $dat); }
echo abb();
create a new file wherein your connection was declare then every time u=you need it just put <?php include 'connection.php' ?> near in your header
also it make your variables as $GLOBALS
<?php
$username='root';
$password='xyz';
$database='abc';
$host='localhost';
function MongoConnect($username, $password, $database, $host) {
$con = new Mongo("mongodb://{$username}:{$password}#{$host}"); // Connect to Mongo Server
$db = $con->selectDB($database); // Connect to Database
}
$collection=$db->movie;
$document = array( "name" =>"Calvin and Hobbes");
$collection->insert($document);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $document) {
echo $document["name"] . "\n";
}
?>
I had installed MONGO DB and tried to test my DB, but I am getting an ERROR
"Internal Server Error 500"
And also my Test.php file have my own content called Hello World, but if I had run the TEST.php file it displays Nothing.
My DB table is not accessing and I wasn't able to retrieve data from my Database.
So Kindly help me out here.
There can be several things wrong.
First - is Mongo driver installed?
Second - your MongoConnect function have no effect. You are defining it and not calling. Plus even if you would call it there would be no effect as $db is only in function scope and not outside.
Third - because function MongoConnect have no effect "$collection=$db->movie;" will result in problem as $db is not defined.
Consult http://php.net/manual/en/mongocollection.insert.php on how to insert data in collection.
Internal Server Error only occured when misspelled in code or some of function called wrongly. Please review ur code.
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.