This question already has answers here:
MySQL error 2006: mysql server has gone away
(32 answers)
Closed 4 years ago.
I'm getting these errors:
Warning: mysqli_query(): MySQL server has gone away in (local db)
Warning: mysqli_query(): Error reading result set's header in (local db)
I am establishing a connection at first:
$connection = new mysqli($server, $user, $pass, $db) or die("unable");
Then this:
$sql = $connection->prepare("INSERT INTO comments (name,mail,homepage,comment,time) VALUES (?,?,?,?,?)");
$sql->bind_Param('sssss',$name,$mail,$homepage,$comment,$time);
$sql->execute();
if($sql){
if(!addPics($connection, $image_content, $mime, $time)){
//other code
}
addPics looks like this:
function addPics($connection, $image_content, $mime, $time){
$sql = $connection->prepare("INSERT INTO pictures (picture, mime, time) VALUES (?,?,?)");
$sql->bind_Param('sss',$image_content,$mime, $time);
$sql->execute();
if($sql){
return true;
} else {
return false;
}
Error occurs at the second sql->execute. My guess is that it's because I'm using the connection for several requests but my knowledge of PHP does not allow me to figure out a solution.
Thank you!
To demonstrate my comments
It would be wise to use backticks around certain column names ( or all ) if they have special meaning within SQL - such as name or time
$sql = $connection->prepare("INSERT INTO comments (`name`,`mail`,`homepage`,`comment`,`time`) VALUES (?,?,?,?,?)");
$sql->bind_Param('sssss',$name,$mail,$homepage,$comment,$time);
/* assign a variable to the `execute` method and test that var */
$result = $sql->execute();
if( $result ){
/* the statement is now finished with, close it */
$sql->close();
if(!addPics($connection, $image_content, $mime, $time)){
//other code
}
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How do I display a MySQL error in PHP for a long query that depends on the user input? [duplicate]
(6 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
Hey can you guys help me with this because I can't figure it out here are the errors.
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_connect(): (HY000/1045):
Access denied for user 'freeload_retain'#'vps28004.inmotionhosting.com'
(using password: NO) in /home/freeloadboard/public_html/insert.php on
line 7
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_select_db() expects
parameter 1
to be mysqli, boolean given in /home/freeloadboard/public_html/insert.php
on line 21
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_query() expects parameter
1 to be mysqli, boolean given in
/home/freeloadboard/public_html/insert.php on line 45
Program:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('##.##.###.##','freeload_retain','');
if(!$con)
{
echo "Not Connected to Server. ";
}
if(!mysqli_select_db($con, 'freeload_retain'))
{
echo "Database Not Selected. ";
}
$Companyname = $_POST['companyname'];
$Username = $_POST['username'];
$Password = $_POST['password'];
$Email = $_POST['email'];
$sql = "INSERT INTO clients (companyname, username, password, email)
VALUES ('$Companyname', '$Username', '$Password', '$Email')";
if(!mysqli_query($con, $sql))
{
echo "Not Inserted. ";
}
else
{
echo "Inserted. ";
}
?>
Hope you guys find out the answer soon!
Also I'm reusing this question because I can't wait another day to make another question but thanks for helping me out!
To answer your question: It's not working because you're wrapping the column names in brackets, remove these and it should work. You also have a typo. ($comapnyname = $_POST['companyname'];), should be $companyname.
However, there's a few other, bigger issues with your code. You're using the mysql functions, which are deprecated and completely removed from PHP7.
Next to that, you should use prepared statements and bind_param to prevent SQL injections, escaping strings will not accomplish this.
This what it would look like using prepared statements.
// ... Set your database connection variables
/*
* Create the database connection, notice the
* usage of mysqli instead of mysql
*/
$connect = new mysqli($host, $user, $password, $database);
/*
* The query, notice the usage of a question mark
* on the place of the variables to be inserted
*/
$sql = "INSERT INTO client (cname, tname, pname, ename) VALUES (?, ?, ?, ?)";
// Prepare the query using $connect->prepare()
$stmt = $connect->prepare($sql);
// Check if the query was prepared
if(!$stmt) {
// ... Handle your error
}
// Get $_POST variables
$companyname = $_POST['companyname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!$stmt->bind_param('ssss', $companyname, $username, $password, $email)) {
// ... Handle your error
}
if(!$stmt->execute()) {
// ... Handle your error
} else {
echo 'Record inserted.';
}
It also seems that you're inserting the passwords into your database as clear-text, this is a big issue. You should hash them. Write two functions, one to hash the password and one to verify it when users log in.
The first function will return the password hash and the second one will return TRUE or FALSE if the password is correct or incorrect.
function hashPassword($password) {
return password_hash($password, PASSWORD_DEFAULT);
}
function verifyPassword($password, $hash) {
return password_verify($password, $hash);
}
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Below is my function listRecordsMatching($accNo) which connects to my mySQL server to match all records that have a specific account number. I know my problem lies in the way I write my SQL.
My table has the following structure: (int)id, (string)cheque-no, (double)amount, (date)cheque-date, (string)customer, (int)account.
NOTE: conn() is a global function in my config file that returns the mysqli object connected to my server.
EDIT: Since the conn() function is leading to some confusion:
EDIT2: I have found the answer. After doing $stmt->execute() I must bind the results to variables to use them. $stmt->bind_results($var1, $var2, ...)
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$GLOBALS['conn'] = $conn;
function conn(){
return $GLOBALS['conn'];
}
function listRecordsMatching($accNo){
//prepare statement
$stmt = conn()->prepare("SELECT * FROM `mfs-cheque-app`.`cheques` WHERE `account` = ?");
$stmt->bind_param('i', $accNo);
$stmt->execute();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row) // outputs NULL
echo "<form id='records'>1";
while(true){
if (!$row) break;
$c = new Cheque($row['cheque-no'],$row['amount'],$row['cheque-date'],$row['customer'],$row['account']);
echo $c->list(); // outputs formatted html
}
echo "2</form>";
}
OUT>>> NULL<form id="records">12</form>
You are using 2 different Variables $accNo and $account ...change one of them to match the other and it will probably start working.
I am wondering if its possible to run an insert query if the answer is correct, I have tried multiple types of queries from creating a new stmt and array and inserting them into the database if the answer if correct, However with my basic understanding of how it all works, I may be missing something? I am not getting any errors returned, just getting the echo statement returned.
Note : I know I am trying to insert QuestionID multiple times its just to put data into the database. It will be updated with the correct fields.
Can anyone enlighten me on whats the issue :
<?php
// establishing the MySQLi connection
require_once('connection-test.php');
$mysqli = new mysqli($host,$username,$password,$database);
if($mysqli -> connect_error)die($mysqli->connect_error);
$questionID = $_POST['id'];
$userAnswer = $_POST['answer'];
$query = "SELECT answers FROM answers WHERE questionID=?";
$statement = $mysqli->prepare($query);
$statement ->bind_param('i', $questionID);
$statement->execute();
$statement->bind_result($answer);
while($statement->fetch()){
if($answer != $userAnswer){
echo "Wrong";
//return to previous Page
}else{
echo "Correct";
mysqli_query($mysqli,"INSERT INTO submissions (submissionsID,teamID,questionID,answer)
VALUES ($questionID,$questionID,$questionID,$userAnswer)");
}
}
$statement->close();
?>
Turns out I had to free_result()before I could run another mysqli statement
This question already has answers here:
Fatal error: Call to a member function fetch_assoc() on a non-object [duplicate]
(4 answers)
Closed 8 years ago.
ok i have been using the mysql format for quite a while but i figured its time to transfer my site over to the new mysqli format now rather then later. im trying to re write my functions to draw stats from the database but i am getting all sorts of errors.
I have looked at countless mysqli tuts but none are very descriptive and im not quite understanding the 2 parameter rule ect. below i posted my function and includes. if anyone can tell m what im doing wrong i would appreciate it.
Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\includes\stat.php on line 7
stat.php
function getStat($stat) {
require_once 'includes/config.php';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = $mysqli->query("SELECT $stat FROM players WHERE username = '".$_SESSION['username']."'");
$row = $sql->fetch_assoc();
$result = $row['$stat'];
return $result;
}
?>
and here is the test page i am using to try and get this working.
test.php
<?php
include 'includes/login-check.php';
include 'includes/config.php';
include 'includes/database.php';
include 'includes/stat.php';
echo getStat('name');
?>
ow and please dont start posting a bunch of comments bashing on the code cause as stated before ive never used mysqli so ide rather read constructive criticism then flames like half the post around here.
Change that in your getStat function.
$result = $row[$stat];
Adapt the following code to best suit your current code...
if ($stmt = mysqli_prepare($link, "SELECT $stat FROM players WHERE username = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_SESSION['username']);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is the current username.");
/* close statement */
mysqli_stmt_close($stmt);
}
This question already has answers here:
Reference — frequently asked questions about PDO
(3 answers)
Closed 9 years ago.
I'm trying to insert values to mysql database, but for some reason this is not working. I can get it to work with normal PHP but I have been told that PDO would be safer to use. This is the code I use, the values are posted to the php file, but not updated to mysql. What could be the reason for that?
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$value1 = $_POST["value1"];
$value2 = $_POST["value2"];
$value3 = $_POST["value3"];
$value4 = $_POST["value4"];
// query
$sql = "INSERT INTO `database`.`table`
(`id`, `value1`, `value2`, `value3`, `value4`, `timeStamp`)
VALUES (NULL, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
$q = $conn->prepare($sql);
$q->execute(array($value1, $value2, $value3, $value4));
?>
Change this line
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
to this
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
and use try catch on
try
{
$q->execute(array($value1, $value2, $value3, $value4));
}
catch(Exception $e)
{
echo $e->getMessage();
//other code to handle exception for example logging, rollback transaction if exists etc.
}
When you make these changes then PDO Exceptions will be thrown and you will see what problem is. With PDO exception you can do more to handle error, for example if you use transactions then you can in catch block rollback it.
You can use error_reporting(E_ALL); and display_errors with ini_set().
You can also use PDO::errorInfo
From manual:
PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
To see examples check this link
Check these links:
how to set display errors
info about exceptions
pdo exception