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.
Hey there i have searched but can not find the answer i am looking for. My form will not post to my database i started getting sql injected so i changed my code around to use $mysqli->real_escape_string but it does not seem to want to still post all i am getting is the error in the code any help would be greatly appreciated.
<form action="" method="post">
<br/>
<input type="text" name="Key" class="dap_text_box" placeholder="Enter Key"/><br/>
<br/>
<input type="text" name="Name" class="dap_text_box" placeholder="Name"/><br/>
<br/>
<input type="text" name="Email" class="dap_text_box" placeholder="Email"/><br/>
<br/>
<input type="text" name="IP_s_" class="dap_text_box" placeholder="Enter IP"/><br/>
<br/>
<input type="submit" name="submit" value="Key Activation" class="sendbutton"/> </form> <hr/> </body> </html>
<?php
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "root", "rkPJNwe0cI", "key");
// Check
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set charset for correct escaping
$mysqli->set_charset('utf8');
echo $_SERVER["REMOTE_ADDR"]; // mmm?
$key = $mysqli->real_escape_string($_POST['Key']);
$IP = $mysqli->real_escape_string($_POST['IP']);
$name = $mysqli->real_escape_string($_POST['Name']);
$email = $mysqli->real_escape_string($_POST['Email']);
$IP_s = $mysqli->real_escape_string($_POST["IP_s_"]);
// (ID, Key, Activated, IP, Banned)
$sql = "INSERT INTO keys (ID, Key, Activated, IP, Banned, Name, Email) VALUES ('$ID1', '$key', 1, '$IP', 0, '$name', '$email')";
$sql1 = "SELECT ID, Key, Activated, IP, Name, Email FROM Keys";
$sql = "UPDATE Keys set IP='$IP_s_', Name='$name', Email='$email', Activated='1' WHERE Key='$key'";
if ($mysqli->multi_query($sql) === TRUE) {
echo "Activated";
} else {
echo "Error";
}
$mysqli->close(); }
You have quite a few things wrong from what I can see. Too long for a comment.
You use multi_query() but only have one query defined in $sql. Your insert statement and select statement don't appear to be doing anything, you overwrite the insert statement before you call multi_query().
$ID1 doesn't appear to be defined anywhere for your insert statement.
Why not use prepared statements? So much easier and efficient than trying to escape each individual string.
Related
I've looked everywhere and I can't find anything helpful. I'm trying to create an online sheep game, and to begin playing the game, the user needs to select the color and name of their first sheep. When submitted, it inserts the data into my MySQL database successfully, but displays this error:
Error: 1
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1' at line 1
Here's my syntax to connect to the database:
<?php
$conn = mysqli_connect("localhost","root","","flyingfeetranch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here's my form and what I use to insert:
<form name="properties" method="POST">
<input type="radio" name="color" value="white" selected="selected">White<br>
Name: <input type="text" name="name" value=" "/>
<input type="submit" name="submitname" value="Submit"/>
</form>
</div>
<?php
if(isset($_POST['submitname']))
{
$Color = $_POST['color'];
$Name = $_POST['name'];
$Age = "12";
$sql = mysqli_query($conn, "INSERT INTO babydolls (name, color, age)VALUES ('$Name', '$Color', '$Age')");
if($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
The "1" stems from querying twice, which means it worked. Had it been a "0", then that'd of been a different ballgame.
Remove one of the querying functions.
Just check with the variable for it.
$sql = mysqli_query($conn, "INSERT INTO babydolls (name, color, age)VALUES ('$Name', '$Color', '$Age')");
if($sql)
{
echo "New record created successfully";
}
Beware, you're open to an sql injection here, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
Note: You should also check for empty fields and checking if a radio is set should you happen to remove the "selected" from it (bit of a side note here). That could cause you problems if none of those fields are not filled and your db doesn't accept empty/null values.
References:
https://php.net/manual/en/function.empty.php
https://secure.php.net/manual/en/function.isset.php
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to php and have written the following php script to write from a FORM. However, the database is not updating. I know that the database connection is okay. Any help would be appreciated.
$name = $_POST["name"];
$lastName = $_POST["last_name"];
$email = $_POST["email"];
$location = $_POST["location"];
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club.users (name, last_name, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
Try this
You have to use the SQL injection for security something like this
$conn->real_escape_string($_POST['name']);
Check your table name.I haven't use table name club.users before because it will display the error like table does't exist. Just use the table name club or users
Time to learn the PHP
https://www.w3schools.com/php/php_mysql_insert.asp
index.php
I hope your HTML code looks like this
<form action="register.php" method="POST" name="register">
<input type="text" name="name" placeholder="Name">
<input type="text" name="lastname" placeholder="Lastname">
<input type="email" name="email" placeholder="Email">
<input type="text" name="location" placeholder="Location">
<input type="submit" name="submit" value="Register">
</form>
Connection.php
If you are working on the local server the used root as username and password should be blank.
$servername = "localhost";
$username = "root";//if you are working on local server
$password = ""; //set blank if you are working on local server
$dbname = "myDB";//your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
register.php
<?php
include('connection.php');// added the connection here
if (isset($_POST['submit'])) {
$name = $conn->real_escape_string($_POST["name"]);
$lastName = $conn->real_escape_string($_POST["lastname"]);
$email =$conn->real_escape_string($_POST["email"]);
$location = $conn->real_escape_string($_POST["location"]);
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club (name, lastname, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
First of all define the db server connection in same php page or you may include the connection. Php file for this purpose.
Secondly it you wish to use MySQL db simple use musql_query($sql, $con) then write below lines of after inserting results.
Sorry I posted it from my mobile if you need I can post you entire code sample from my PC.
I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')
I am using PHP to try and update information I have in a mysqli table. I have decided to try and use mysqli rather than mysql. Unfortunately I cant seem to find my answer anywhere because im also trying to complete it Procedural style, as I have no knowledge of OOP and all tutorials (that i have found) are in OOP.
Below is the script I have created. I have added comments to say what I think each command is doing.
<?php
DEFINE('DB_USER', 'root');
DEFINE('DB_PASS', 'password');
DEFINE('DB_NAME', 'test');
DEFINE('DB_HOST', 'localhost');
//connect to db
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_connect_error($dbc));
mysqli_set_charset($dbc, 'utf8');
//form not submitted
if(!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE people_id = $_GET[id]";//compares id in database with id in address bar
$r = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r, MYSQLI_ASSOC);//returns results from the databse in the form of an array
}else{//form submitted
$q = "SELECT * FROM people WHERE people_id = $_POST[id]";//compares id in database with id in form
$r2 = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);//returns results from the database in an array
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$hobby = $_POST['hobby'];
$id = $_POST['id'];
//mysqli code to update the database
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
//the query that updates the database
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
//1 row changed then echo the home page link
if(mysqli_affected_rows($dbc) == 1){
echo "home page";
}
}
?>
The update form
<form action="update.php" method="post">
<p>First name<input type="text" name="fname" value="<?php echo "$person[people_fname]" ?>" /></p>
<p>Last name<input type="text" name="lname" value="<?php echo "$person[people_lname]" ?>" /></p>
<p>Your age<input type="text" name="age" value="<?php echo "$person[people_age]" ?>" /></p>
<p>Your hobby<input type="text" name="hobby" value="<?php echo "$person[people_hobby]" ?>" /></p>
<input type="hidden" name="id" value="<?php echo $_GET['id'] ?>" />
<input type="submit" name="submit" value="MODIFY" />
</form>`
When I submit the form I get the following error message
Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\sandbox\update.php on line 39
I realize this is telling me the issue is with
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
So I have tried to put the sqli code in as the second parameter (i realize this is the same as putting the variable in, but it was a last resort), but it didn't seem right and still didn't work. I have also looked a php.net but couldn't work out the answer from the example they have given
Please advise, I thought this was meant to be simple?
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
You need to quote out the variables:
$update = "UPDATE people
SET people_fname = '$fname',
people_lname = '$lname',
people_age = '$age',
people_hobby = '$hobby'
WHERE people_id = '$id'";
HOWEVER
You should look into bound parameters - you're taking user input and writing it straight into your database, which means that a malicious user can do all sorts of mischief.
Have a look at the manual page for mysqli's bind_param - there are plenty of example code snippets.
Don't pass $r to mysqli_error. It accepts an optional mysql link, but not a query result anyway.
In your case, the query is executed. That evaluates to false, which is assigned to $r. The assignment evaluates to false, causing you to call die(mysqli_error($r)) with $r being false.
I think you meant to pass $dbc to mysqli_error.
Looks to me like the problem is with the database connection ($dbc). Because you are using
#mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME)
The '#' may be hiding the connection error somehow.
Also, please tell me you're doing data sanitisation in real life, right? If not, you have to run mysqli_real_escape_string() on all the POST and GET data.
you wrote
//returns results from the database in an array
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);
but you should write
//returns results from the database in an array
$person = mysqli_fetch_array(MYSQLI_ASSOC);
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database. I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.
Here's the latest version of the code. Could someone please tell me what I am doing wrong?
* Basic HTML Form *
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
* Processor File *
<?php
$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
Print "Your metrics have been successfully added to the database.";
mysql_close($con);
?>
Your mysql-syntax is wrong.
Try
INSERT INTO my_metrics
SET
date = '$date',
metric1 = '$metric1',
metric2 = '$metric2'
Depending on what the table looks like, your code may or may not work,
"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
assumes that the fields are in that order, and that there are no fields before this one.
"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
would be more future proof, and may also solve your problem as they are going to insert into the correct fields.
It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.
When connecting to the database, you write
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
You can simplify this, and making this more readable by writing
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:
"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
And finally, here's a speed concideration.
There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code
$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'
echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'
echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although
echo "the cat is $age years old"
is shorter to type than
echo 'the cat is '.$age.' years old';
it will boost your page loading when you write larger applications.
Hooray! Hooray! Hooray!
Thank you all for such helpful advice! It finally works! Here's the updated code in case any other newbies have the same issue. (Hope I didn't screw anything else up.)
Form
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Processor
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
// 1. Create connection to database
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$date=mysql_real_escape_string($_POST['date']);
$metric1=mysql_real_escape_string($_POST['metric1']);
$metric2=mysql_real_escape_string($_POST['metric2']);
// 4. Insert data into table
mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
Here you go love :) try W3c it a good place for new pepps
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO my_metrics (date, metric1, metric2)
VALUES
('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your metrics have been successfully added to the database.";
mysql_close($con)
?>