This is my code, we have database called "our_new_database".
The connection is fine, as well as the HTML Form and credentials and I still cannot insert information into the database.
Table is created, I can see the columns and lines in XAMPP / phpMyAdmin.
The only error I'm getting is the last echo of the If/Else Statement - "Could not register".
Tried everything I can and still cannot make this insertion to work normally.
Can someone advise me something?
<?php
include "app".DIRECTORY_SEPARATOR."config.php";
include "app".DIRECTORY_SEPARATOR."db-connection.php";
include "app".DIRECTORY_SEPARATOR."form.php";
$foo_connection = db_connect($host, $user_name, $user_password, $dbname);
$sql = "CREATE TABLE user_info(
user_name_one VARCHAR(30) NOT NULL,
user_name_two VARCHAR(30) NOT NULL,
user_email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($foo_connection, $sql)){
echo "Table created successfully";
}
else {
echo "Error creating table - table already exist.".mysqli_connect_error($foo_connection);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user_name_one = $_POST["userOne"];
$user_name_two = $_POST["userTwo"];
$user_email = $_POST["userEmail"];
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
if(mysqli_query($foo_connection,$sql))
{
echo "Successfully Registered";
}
else
{
echo "Could not register";
}
}
$foo_connection->close();
You should avoid the direct use of variables in SQL statements, instead, you should use parameterized queries.
This also should avoid the need to string concatenation and manipulation problems.
$stmt = $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$stmt->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$stmt->execute();
You need to change
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
To
$sql = "INSERT INTO `user_info`(`user_name_one`,`user_name_two`,`user_emai`l) VALUES ('$user_name_one','$user_name_two','$user_email')";
remember you should use prepared query
$sql= $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$sql->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$sql->execute();
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
I reckon your parentheses on this line:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
Do not match, it should look like something like this:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
Cause for know your query is:
"INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('value',('value1',('value2')"
As said above you might use:
echo $foo_connection->error
To see some errors displayed
Related
So im trying to get my data from my form submission to be put into a mysql database but whenever i submit a form it gives me this error: Error: INSERT INTO form_submissions(ID, first, last, phone, class) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
Now here is my PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_database";
$value = $_POST['first'];
$value1 = $_POST['last'];
$value2 = $_POST['phone'];
$value3 = $_POST['class'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])";
if ($conn->query($sql) === TRUE) {
echo "Submitted Successfully";
} else {``
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
assuming that ID is auto-incrementing, and that the others are text,
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,
`class`) VALUES ('$value','$value1','$value2','$value3')";
Your query should be like:
INSERT INTO `form_submissions`(`first`, `last`, `phone`, `class`)
VALUES ('John','doe', '98564', 'SOMECLASS');
To check: echo the $sql query and debug it in phpmyadmin.
Note: If you enabled AUTO_INCREMENT, you can ignore the data feed of that column. It will do its job automatic.
Security tip - >
To prevent SQLi Injection check out this post.
There are two things wrong.
The first thing is you give 5 fields (ID, First, last, phone, class)
And you only have 4 variables in your post. I think you don’t need to send the ID on an insert if the column is set to auto increment in the database, So don’t send an value for the ID field.
Your variables are not correctly inserted in the query.
The [value-1] douse not mean the $value1 variable will automatically be injected in there.
This can be done in a lot of way’s
I wil give you a simple solution, (but it wil be a bad one for real websites). The simple solution is:
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,`class`) VALUES (`$value`,`$value1`,`$value2`, `$value3`)";
The reason this is bad is: You are directly entering post data inside your query and are now vounerable to SQL-Injections. You need to escape your post data befoure inserting it in a query. Or better yet don’t use ‘mysqli’ but an PDO.
An good PDO example can be found here
https://www.w3schools.com/php/php_mysql_insert.asp
I hope this helps.
Your SQL is apparently wrong. It should look's like with something like that:
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ($value1,$value2,$value3,$value4,$value5)";
The field ID should be auto_increment. If it is, you don't need to pass value to it.
I've combed through this site non-stop looking for the solution to my problems but have come up empty handed still.
Here's the problem, whenever I use the following INSERT INTO statement nothing is inserted into my database, the code runs without a hitch but at the end of the day my database is still empty(excluding values I manually inserted myself).
I would also like to point out that I ran a SELECT FROM statement that returned manually inserted values from the database nicely.
Anyway here's the code:
Connecting to database
$link = mysqli_connect("localhost", "root", "", "prototype");
Insert code
if ($error) echo "There were error(s) in your signup details:".$error;
else
{
$query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
echo $results;
if ($results) echo " This email address is already taken. Would you like to log in?";
else
{
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email']).', '.md5(md5($_POST['email']).$_POST['password'])."')";
mysqli_query($link, $query);
echo "You've been registered!";
$_SESSION['id'] = mysqli_insert_id($link);
print_r($_SESSION);
// Redirect to logged in page
}
Try to change your insert query as below
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".md5(md5($_POST['email']).$_POST['password'])."')";
I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php
Ok so my insert should be fine but is returning false, $quote holds value i have checked. and my database is here Hope another pair of eyes can spot this. I have been using the same insert style for the other php files, works fine. But this one is tricky...issit because of the foreign keys?
<?php
$quote = $_POST["quote"];
require "init.php";
$query = "INSERT INTO `quote`(`quote_description`) VALUES('".$quote."');";
$result = mysqli_query($con,$query);
//"INSERT INTO `quote`(`quote_description`) VALUES ('".$quote."');";
if($result)
{
$response = array();
$code = "submit_true";
$message = "Quote success, Click Ok to continue";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else{
$response = array();
$code = "submit_false";
$message = "Sorry, some server error occurred, please try again";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
mysqli_close($con);
?>
I am getting the following error after checking for errors:
Cannot add or update a child row: a foreign key constraint fails (mydb.quote, CONSTRAINT fk_quote_user FOREIGN KEY (user_id) REFERENCES user (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
When using INSERT in MySQL, you have to include all columns and values to be inserted. Try this;
$query = "INSERT INTO quote(quote_id, quote_description, quote_points, user_id, Quote_of_day_id) VALUES(NULL, '".$quote."', '".$points."', '".$user_id."', '".$qod_id."');";
If you don't have all the values to be inserted at time for this query, just set them to nothing. To add values later use UPDATE:
$query = "UPDATE quote SET user_id = 8 WHERE quote_id = 6";
Though this is a solution for inserting, it is insecure and vulnerable to sql injection. Here is the better object-oriented solution that is more secure, and I suggest using it over any other insecure INSERTS:
$db = new mysqli($host, $user, $pass, $database);
$stmt = $db->prepare('INSERT INTO quote(quote_id, quote_description, quote_points, user_id, Quote_of_day_id) VALUES(?, ?, ?, ?, ?);');
$stmt->bind_param('isiii', $quote_id, $quote, $points, $user_id, $qod_id);
$stmt->execute();
Also it is a good idea to add this to handle your POST data:
if(!isset($_POST["quote"])) {
echo "Data not received correctly";
exit();
}
Hope these examples help you. Wish you the best.
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with