Mysqli stopped working because of fetch issue - php

I have just come back to a project that was working fine a month ago. Today I have found im getting a "Warning: mysqli::query(): Couldn't fetch mysqli" error and I have no idea why. I have tried changing the if statement but I still get the same result.
php page
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_SESSION['email'];
$name = $_SESSION['name'];
$hash = $_SESSION['hash'];
$password = $hash;
echo $name;
echo '<br>';
echo $email;
echo '<br>';
echo $hash;
echo '<br>';
$sql = "INSERT INTO signed_up(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
//if ($result = $mysqli->query("INSERT INTO `signed_up`(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')")){
//
//header('location: ../register_success.php');
//// $result->close();
//
//}
//else {
// echo "error";
//}
?>
The error im getting
you have succesfuly connected to the database
gptgeoff
up666315#myport.ac.uk
$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe
Warning: mysqli::query(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 24 Warning: main(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 27 Error: INSERT INTO signed_up(name, email, password) VALUES ('gptgeoff', 'up666315#myport.ac.uk', '$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe')
The db_connect.php file works because I'm getting the "you have succesfuly connected to the database" displaying, the session variables are being passed and echoed out in both the echo statements and in the values of the $sql query so I am unable to understand why this has stopped working, can anyone advice please
db_connect.php
<?php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if(!$mysqli) {
die('error connecting to database');
}
echo 'you have succesfuly connected to the database'.'<br/><br/>';
?>

This line:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
creates an object. It is an instance of the class mysqli. An object will always be true. Your if statement checks if $mysqli is false. This if statement is wrong, because whether the connection was successful or not the object will never be false.
Do not check for connection errors manually. Your connection failed and when it did PHP threw a warning. Please check your PHP configuration for error reporting, because you have probably warnings silenced. Also please enable mysqli error reporting. Insert this line before creating an instance of mysqli.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Related

HTTP error when trying to access mysql database

Hey guys I'm still learning PHP and need help. I have 3 files that require a database.php file to connect to MySQL. when I execute the files only two of them work. For the last file, I get an HTTP error 500.
<?php
require( 'database.php');
// inserting information from the form into the database
$sql = ("INSERT INTO guestlist (firstName, lastName, phoneNumber,guests,event)
VALUES (?,?,?,?,?)");
// values are prepared to bind
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"sssss",$_POST['first_name'],$_POST['last_name'], $_POST['phonenumber'], $_POST['guest'], $_POST['event']);
$stmt->execute();
if (!$stmt)// Was not updated
{
// shows error
echo("There was an error with your RSVP. Please try again.");
mysqli_stmt_close($stmt);
}
else //Was updated
{
echo("Your RSVP has been completed.");
}
//End database connection
mysqli_close($con);
?>
this is my database file that was provided by my professor
<?php
$myHost = "localhost"; // localhost, do not change this string
$myUserName = "cmorales"; // CHANGE TO YOUR USERNAME
$myPassword = ""; // CHANGE TO YOUR PASSWORD
$myDataBaseName = "cmorales_project"; // CHANGE USERNAME
username_project
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword",
"$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ".
mysqli_connect_error());
}
?>
Because there is a syntax error in your database.php
Cause :
No semicolon end of username_project 7th line.
Solution:
remove undefined constant username_project on the 7th line.
as #Antonio Teh Sumtin mentioned in the comments, Always check the error log or enable the display error during development.

mysqli_connect() isn't selecting database? and can't insert data

I've got this code
<?php
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="mydb";
$db_connect=mysqli_connect($db_host, $db_username,$db_password, $db_name);
//check connection
if (mysqli_connect_error()){
echo "Failed to connect to MySQL:" .mysqli_connect_error();
} else{
echo "Connection successful" ;
}
?>
When i run the code it shows "Connection successful" but when i input data into a table that is in the database it gives me an error "No database selected"
I tried the code below and it seems to work, other than the fact that the Auto increment value (ID) isn't passed into the database so it gives me an error which means that "the data passed in row 1 doesn't match the datatype. "(Shouldn't it not be required to be entered, and with each insert query gets updated automatically?) I am passing values to the table using and insert statement and not in array form, maybe?
<?php
error_reporting(1);
$connect_error = 'Sorry, we\'re experiencing connection problems.';
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('mydb') or die($connect_error);
?>
I was asked to provide the code i'm using for inserting data into the table.
<?php
require_once ('dbconnect.php');
$title= "my title";
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$class = $_POST['class'];
$type = $_POST['type'];
$description = $_POST ['description'];
$date = date(d-m-y);
$sql= "INSERT into mytable values ('username, password, class, type, description')" ;
$qry= mysql_query($sql) ;
if (!$qry) {
echo "Something went wrong: " . mysql_error();}
else echo "Finished successfully";
}
?>
Are you mixing mysqli and mysql.
use below code to fire mysql query
mysqli_query($db_connect,$sql);
replace this line
$qry= mysql_query($sql) ;
to
$qry= mysqli_query($db_connect,$sql);
Latest Version of php uses mysqli object (mysql improved) insted of methods for accessing mysql database.
<?php
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="mydb";
$db_connect=new mysqli($db_host, $db_username,$db_password, $db_name);
//check connection
if ($db_connect -> connect_error)
{
echo "Failed to connect to MySQL:".$db_connect->connect_error;
}
else{
echo "Connection successful" ; }
?>
I had two mistakes, one was mixing mysqli in the dbconnect.php while using mysql_query in the other page. And then I was confused about the second parameter to use with mysqli_query other than the insert statement, used the connection variable and it now works.

Inserting data into SQL table from HTML form

A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!con) {
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')) {
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.
You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.
Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!$con){
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')){
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
mysqli_stmt_execute($stmt);
echo "Data inserted";
}
else {
echo "Error";
}
mysqli_close($con);
//header("refresh:2; url=form.html");
?>
I think it should work, if not let me know.
Try this :
<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

PHP not inserting data into MySQLi database

My php has connected to my database however when I try to insert the data, I get the query is not okay response.
if(isset($_POST['Register'])) {
session_start();
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$query = "INSERT INTO user (Fname, Lname, Email, Password) VALUES('{$FName}', '{$LName}', '{$Email}', '{$PW}')";
$result=mysqli_query($con, $query);
if($result){
echo "Query is successfully executed";
}else{
echo "Query is not ok";
}
}
?>
This is my connection code but it tells me that I am successfully connected.
$con = mysqli_connect("localhost", "*******","*******");
mysqli_select_db('batman',$con);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
The database matches all of the inputs and the table name is user so I cannot figure out why it will not insert into the database.
Use error_reporting(E_ALL); at startup
&
use simple $Fname instead {$Fname}
Also check input type="submit" and name=" is name Register"
Maybe you could try to make a class with the script, because I think the problem is the connection that you use , because you are not calling for the connection function when you execute the query.
Regards!

Message on successful database entry

I'm trying to display a message upon a successful user registration however what I have doesn't seem to be working and just submits/refreshes the page. No message pops up even though data has successful been entered into the SQL database. Any tips or ideas?
<?php
require('php/connect.php');
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
$result = mysql_query($query);
if($result){
echo $msg = "Successful Registration!";
}
}
?>
Learning PHP currently so sorry if there's a really obvious answer here!
Edit: Forgot to include echo. Just needed a second pair of eyes, sorry guys. Thanks for the tips!
First of all have this on consideration:
If you're getting started on PHP, please stop using mysql. It's deprecated, instead, you can use either PDO or MySQLi
As for your issue, your message is not being printed. Please make sure you echo the $msg variable:
$msg = "Successful Registration!";
echo $msg;
In mysqli a standard connection would be:
$DBConnect = new mysqli('serverName', 'userName', 'userPassword', 'dbName');
And that's it, that's all you need to start querying your database using mysqli.
For a mysql connection, try debugging it, see if there's a connection:
$connection = mysql_connect('localhost', 'userName', 'userPassword');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
Try to echo message
if($result)
{
echo $msg = "Successful Registration!";
}
<?php
echo "Successfully registered!";
?>

Categories