Php Simple Error [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to insert data into a database through php.. Easy enough (I thought). I can't figure out what I am doing wrong. Here is my code:
$DB_HostName = "localhost:8888";
$DB_Name = "Sample";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "Check";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "INSERT INTO $DB_Table (name) VALUES ('Sally') ";
mysql_query($sql) or die ("Error with Result");
mysql_close($con);
It gives me an error saying "Error with Result". This means that it must be connecting to the database correctly and everything is working right except for the end part.. What am I missing? If I say (msql_error()) it also does tell me to check the $sql. I can't figure out though what I am typing in wrong.

escape your database name with backtick
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";
or
$sql = "INSERT INTO `" . $DB_Table . "` (name) VALUES ('Sally') ";
CHECK is a MySQL Reserved Keyword.
MySQL Reserved Keyword List
How can I prevent SQL injection in PHP?

I can't stress this enough, don't use mysql_ functions, that time has gone. Use either mysqli or PDO.
A simple way to check what is wrong with your SQL query is to add an error flag on the end of your die statement mysql_query($sql) or die ("Error with Result<br>".mysql_error());
It appears in your case that check is a constraint used to limit the value range that can be placed in a column. You would need to identify that it is a table using "`":
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";

Related

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))."')";

What mistake i have in condition with PHP and MySQL? [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I'm working on a little browser game, but when I have a condition in connection to MySQLi database, it doesn't work.
In else closure it should write $name, but it doesn't.
if ($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
else{
//IF CONNECTION IS GOOD, GET DATA FROM DATABASE
$query = "SELECT name, separator, description, maintenance FROM configuration";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
//this ↓↓↓
echo $name;
}
Use back ticks (``) when using reserved words.
From,
$query = "SELECT name, separator, description, maintenance FROM configuration";
To,
$query = "SELECT name, `separator`, description, maintenance FROM configuration";
Try with backticks:
$query = "SELECT name, `separator`, description, maintenance FROM configuration";

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

Categories