Mysqli error while callling second function in the same file [duplicate] - php

This question already has answers here:
error in calling same function twice in php
(2 answers)
Closed 2 years ago.
<?php
function insertData()
{
include_once 'database/connection.php';
echo "<br>============= Insert Data =================<br>";
try{
$sql = "INSERT INTO table1 (activity_date, activity_name, activity_point) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $activity_date, $activity_name, $activity_point);
// set parameters and execute
$activity_date = "06-APR-2020";
$activity_name = "Test";
$activity_point = "5";
$res = $stmt->execute();
var_dump("<br>Res:- ".$res);
print_r("<br>Result:- ".$res);
if ($res) {
echo "<br>Id:- ".$conn->insert_id;
echo "<br>New records created successfully";
}
else{
echo "<br>New records not inserted successfully";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
// insertData();
function selectData()
{
include_once 'database/connection.php';
echo "<br>============= Select Data =================<br>";
try{
$sql = "SELECT * FROM table1 WHERE activity_id > ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $activity_id);
// set parameters and execute
$activity_id = 6;
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$result = $stmt->get_result(); //
$rows = $result->num_rows;
if ($rows > 0){
while ($data = $result->fetch_all())
{
// var_dump($data);
var_export($data);
echo "<br>";
print_r($data);
}
}
else{
echo "Data Not Found";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
selectData();
?>
The insert function call correctly and data is also inserted correctly.
After inserting I am closing the connection in the finally block.
But at the same time calling selectData() function I got an error.
Undefined variable: conn and Undefined variable: stmt.
How should I reopen the connection for second function?

As you use include_once for your database connection inside the function, this will only load the script the first time. Also at the end of the function you close the connection...
$conn->close();
The second time it calls the function, the include is not done again and the connection is closed, so the connection is not re-made.
You should only create 1 connection for the entire script (rare exceptions may apply). So at the start of your script use the include and then pass the connection to any function/class which need to use it.
include_once 'database/connection.php';
insertData($conn);
Add the parameter to your functions...
function insertData( $conn )
and leave the closing of the connection to the system.
One last thing, which is more my preference is to use require_once or require rather than include_once or include as they will stop the script if the file cannot be found.

Related

Function fetch() when I want to check [duplicate]

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()

How can I collect result from prepare statement PHP? [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I can't collect the results of my query in this function :
<?php
function getBestScore()
{
require_once ('connection.php');
$idJoueur = session_id();
if ($stmt = $conn->prepare('SELECT bestScore FROM Player WHERE ID = ?'))
{
$stmt->bind_param('i', $idJoueur);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();
$bestScore = $data;
if (!(empty($bestScore)))
{
header("Location: ../index.php");
}
return $bestScore;
}
else
{
$error = $conn->errno . ' ' . $conn->error;
echo $error;
}
}
My connection works, I tried fetch_assoc(), store_result() but I failed every time.
If you want to select data then try the following
if ($stmt = $conn->prepare('SELECT bestScore FROM Player WHERE ID = ?')) {
$stmt->bind_param('i',$idJoueur);
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
if (!(empty($result))) {
header("Location: ../index.php");
}
return $result;
}
Hope this helps.

PDO not working if I re-run a function inside itself

I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.
Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.
If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).
function generateNumber()
{
global $conn;
$rand = strtoupper(substr(uniqid(sha1(time())),0,5));
$result = date("Ydm") . $rand;
$SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
$c = $SQL->fetch(PDO::FETCH_ASSOC);
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
} else {
$sql2 = "INSERT INTO test (code) VALUES (?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result]);
return $result;
}
}
try {
$conn = new PDO("sqlite:db"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo generateNumber();
}
catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$conn = null;
?>
There are no error messages in the console, but I suspect the problem is this part of the code:
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
}
Any idea how I can write this function in a better way?
Solution :
if ($c['code'] > 0) { // test if $result is already in the database
// if the code exists in db the function return nothing
// because you are missing a return :
return generateNumber();
}

Call to a member function fetch() on boolean [duplicate]

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()

How to display the number of rows using the SQL query COUNT

When I run this query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin it returns the number of rows in my database which is what I want but now I want this number to be displayed on my success.php page using the count method below.
Heres my code so far:
Database.class.php
<?php
include 'config/config.php'; // Inlude the config file, this is where the database login info is stored in an array
class database {
private $dbc; // Define a variable for the database connection, it's visabiliatly is set to 'private' so only this class can access it
function __construct($dbConnection){
// Running the __construct() magic function,
// I am passing through a variable into the contruct method which when the object is created will hold the login details from the $dsn array in config.php
$this->dbc = $dbConnection; // This is saying that the variable $dbc now has the same value as $dbConnection ($dsn array)
$this->dbc = mysqli_connect($this->dbc['host'], $this->dbc['username'], $this->dbc['password'], $this->dbc['database']);
// ^ Running the mysqli_connect function to connect to the database.
if(mysqli_connect_errno()){ // If there is a problem connecting it will throw and error
die("Database connection failed" . mysqli_connect_error());
} else {
echo "allgood";
}
}
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
}
function count($countSQL){ // This is the method used for counting
mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
}
}
?>
Success.php
<?php
include 'classes/database.class.php';
include 'config/config.php';
echo '<h2>Success page</h2>';
$objdb = new database($dsn);
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$objdb->insert($insertSQL);
$countSQL = "SELECT COUNT(ID) FROM blog_posts";
$objdb->count($countSQL); // Executes the query, now how do I display the result? I have tried 'echo'ing this but it doesn't seem to work
?>
Actually its much better to add an alias in your query:
$countSQL = "SELECT COUNT(ID) as total FROM blog_posts";
$result = $objdb->count($countSQL);
echo $result['total'];
Then, on your methods:
function count($countSQL){ // This is the method used for counting
$query = mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
$result = $query->fetch_assoc();
return $result;
}
Additional Info:
It might be good also on your other methods to put a return value. So that you'll know that it worked properly.
Example:
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
$query = mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
return $this->dbc->affected_rows;
}
So that here:
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$insert = $objdb->insert($insertSQL); // so that its easy to test if it indeed inserted
if($insert > 0) {
// hooray! inserted!
}

Categories