PHP mysql error when running INSERT [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
Can someone help me understand this error?
Fatal error: Call to a member function bind_param() on a non-object in C:\MAMP\htdocs\MyCMS\insert_posttwo.php on line 64
<?php
$mysqli = mysqli_connect("localhost", "root", "root", "mycms");
if (isset($_POST['submit'] )) {
$post_author = $_POST['post_author'];
$stmt = $mysqli->prepare ("INSERT INTO 'posts' ('post_author') VALUES(?)");
$stmt->bind_param('s', $post_auth);
$post_auth = $post_author;
$stmt->execute();
echo "<script>alert('Post has been published')</script>";
echo "<script>window.open('insert_post','_self')</script>";
$stmt->close();
}
?>

Instead of single quotes ' use backticks ` to escape field or table names .
$stmt = $mysqli->prepare ("INSERT INTO `posts` (`post_author`) VALUES(?)");

Change this (For columns you have to use back ticks not single quotes):
'posts'
to:
`posts`
Also you have to create a object and not the procedural method otherwise you can't do that so use this:
$mysqli = new mysqli_connect("localhost", "root", "root", "mycms");
//^^^ See here so you create a object
And also you have to close your connection like this:
$mysqli->close();
//^^^^^ Close the connection and not the stmt

Related

MySql Query - reference to ask [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
I want to query one new to sql table, the code run but it doesn't insert anything into the database.
I try to read back the pdo manual but doesn't understand which part I am wrong.
$query = "INSERT INTO 'easycomputing'('STID', 'NAME', 'TONG') VALUES (:STID, :NAME, :TONG)";
$dns = " mysql:host=localhost;dbname=phan1";
$username="root";
$password= "";
// $password="";
try{
//access the database
$db = new PDO($dns, $username, $password);
//execute the query
$statement = $db->prepare($query);
$statement->bindValue(':STID', 137, PDO::PARAM_INT);
$statement->bindValue(':NAME', 'tenten', PDO::PARAM_STR);
$statement->bindValue(':TONG', 5, PDO::PARAM_INT);
//execute the query
if( $statement->execute() ){
echo "record tranfer successfully";
}else{
echo "fail to execute the record";
}
Sorry, but I think that you shouldn't isert the name of columns between codes : (STID, NAME, TONG)

how can I insert data into table php/mysql? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I'm making a quiz and once the calculation of the grade is finished, I want to add that data to test_attempt table.
Here's its structure.
Here's the code of the query:
<?php
$connection = mysqli_connect("localhost", "root", "", "vartvald");
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
}
$user=$_SESSION['user'];
$userid=$_SESSION['userid'];
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
('',null,'$grade','$top_grade','$userid','$fk');";
var_dump($sql);
$connection->close();
?>
What am I doing wrong?
You have few mistakes. Your main problem is that you never prepared any query and never executed it. To do it you need to use prepare(), bind_param(), and execute(). Also you are not opening the mysqli connection correctly and your error checking will never work (Please read: Should we ever check for mysqli_connect() errors manually?)
After fixing your errors your code would look something like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli("localhost", "root", "", "vartvald");
$connection->set_charset('utf8mb4');
$user = $_SESSION['user'];
$userid = $_SESSION['userid'];
$stmt = $connection->prepare('INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES(NULL,NULL,?,?,?,?)');
$stmt->bind_param('ssss', $grade, $top_grade, $userid, $fk);
$stmt->execute();
I have not validated whether your SQL is correct in itself, but if you have error reporting switched on, PHP should tell you if you have a mistake.
Your code will never add data in the database because you aren't calling any funciton that insert data:
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
('',null,'$grade','$top_grade','$userid','$fk');";
var_dump($sql);
// missed code to insert data in the database
$connection->close(); // here you close the connection
Before closing the connection, call mysqli_query:
mysqli_query($connection,"$sql");
Try this:
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
(CURRENT_TIMESTAMP,null,'$grade','$top_grade','$userid','$fk');";
Try the following, here you can see that the CURRENT_TIMESTAMP is passed as first params for data and also below the $sql you can see the mysqli_query which is useed here to execute the insert query.
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
(CURRENT_TIMESTAMP,null,'$grade','$top_grade','$userid','$fk');";
mysqli_query($connection, $sql);

Inserting into MySql DB with PHP not working [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I am trying to insert data into a MySQL database using PHP. As far as I can see I am using the correct code, but it is not inserting - nothing changes in phpMyAdmin. Am I doing anything wrong? (I changed the database name and password here just for safety- it connects without any issues)
<?php
$link = mysqli_connect("localhost", "dbname", "password", "dbname");
if (mysqli_connect_error()) {
die ("Error connecting to the database");
}
$query = "INSERT INTO 'users' ('email', 'password')
VALUES ('example#example.com', '12345678')";
mysqli_query($link, $query);
?>
Use backticks `` instead of single quote ':
$query = "INSERT INTO `users` (`email`, `password`)
VALUES ('example#example.com', '12345678')";

PHP - Entering data into a database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've recently trying to add data into a database, (New to php), I've looked over to see where I've gone wrong, but can't find anything. The error is:
Unknown column 'FUMUKU' in 'field list'
Code:
$dbhost = 'localhost';
$dbuser = 'evocityi_admin';
$dbpass = 'password';
$database = 'evocityi_stocks';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $database);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$Dtime = "30/04/16";
$StockName = "FUMUKU";
$FUMUKUPrice = 1000;
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('$StockName,$FUMUKUPrice, $DTime')";
mysql_select_db('evocityi_stocks');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
SQL Database:
https://gyazo.com/fc97b686cfea79ea773d1796e912551e
Use this It will helps you.
$sql = "INSERT INTO stocks(Stock,Price,TimeD) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";
'$StockName,$FUMUKUPrice, $DTime'
You should surround every variable with quotes:
'$StockName' ,' $FUMUKUPrice' , '$DTime'
Just know that when blindly concatenating variables into a SQL query and not preparing statements for user input makes your code vulnerable to SQL injection. Use Prepared Statements instead. Also, use the mysqli_* functions, the mysql_* functions are deprecated.
Try this query, you are not using qoutes properly on the variables due to this It through error.
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('".$StockName."', '".$FUMUKUPrice."', '".$DTime."')";
To avoid deprecation and SQL Injection you should use PDO or mysqli.
You're using mysql_* functions, that's what's wrong.
Read the documentation and look into alternatives.
One such alternative may be:
$query = $pdoconnection->prepare("
insert into `stocks`
(`Stock`,`Price`,`TimeD`)
values (?,?,?)
");
$query->execute([$StockName, $FUMUKUPrice, $Dtime]);
Try this
$sql = ("INSERT INTO stocks (Stock,Price, TimeD)
VALUES('$StockName', '$FUMUKUPrice', '$DTime')");
I managed to fix it using:
$sql = "INSERT INTO `stocks` (`Stock`,`Price`, `TimeD`) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";

MySQL PDO Query not returning results [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
I know the connection works as i have used this to insert data into the tables but i cant seem to pull it out. Any help would be greatly appreciated.
//Gets id from url
$projectid = $_GET['id'];
try{
// DB CONNECTION
$link = $database->connection;
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query for projects
$q = ("SELECT * FROM projects WHERE id=':pid'");
$prep = $link->prepare($q);
$array = array(
':pid' => $projectid
);
$prep->execute($array);
}catch(PDOException $pde){
echo $pde->getMessage();
die();
}
//Method to retrieve results
while ($r = $prep->fetch()) {
echo $r['projectname'];
}
When you are using PDO with prepared statements, you don't need the single quotes around the pid term. PDO automatically inserts those for you. Just do:
$q = ("SELECT * FROM projects WHERE id = :pid");

Categories