I am programming an App and I have a problem now.
When I register a new student with the app a Query runs on my php Script and insert the new student in my database.
What I want to do now is, when I am registering him, I want my php Script to run a multiple query so that all the other tables should be filled with NULL and the query should get the ID from the new created student to link it with the other tables(foreign key).
I tried it with mysqli_multiple_query and LAST_INSERT_ID() but both didn't work.
How would it be possible to get that id in return from my insert?
Here is my php script.
<?PHP
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown) VALUES('$Name','$Surname','$Street','$Hometown')";
$sql .= "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES ("","","","","",LAST_INSERT_ID())";
if(mysqli_multi_query($con,$sql)){
echo 'successfully registered';
} else {
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I hope someone can help me.
Don't concatenate the two queries. Execute the first, save the last id into a variable like
$id = mysqli_insert_id();
, then execute the second query referencing the variable among the values.
Be aware that if those $_POST variables come from a user submitted form it would be useful to do some validation on them before saving them into database. Maybe this answer would be a nice read ;)
I have modify your code. Try and see if it works for you.
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown)VALUES('$Name','$Surname','$Street','$Hometown')";
mysqli_query($con, $sql);
$id = mysqli_insert_id($con);
if ($id) {
$sql = "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES (NULL, NULL, NULL, NULL, NULL, $id)";
mysqli_query($con, $sql);
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
Related
I have created a if statement that is to check if a username is stored on the SQL database, I am not sure why when it checks the database it always finds that there is a username already inserted even when the database can be empty.
I have tried various variations of an if statement and I am not having much luck.
<?php
if(isset($_POST['save'])){
include 'includes/config.php';
$fname = $_POST['fname'];
$pass = $_POST['pass'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$location = $_POST['location'];
$check = "SELECT email FROM client WHERE email = '$email'";
$res_e = mysqli_query($db, $check);
if (mysqli_num_rows($res_e) == 0) {
echo "<script type = \"text/javascript\">
alert(\"Sorry... username already taken.\");
window.location = (\"signup.php\")
</script>";
} else {
$qry = "INSERT INTO `client`
VALUES('NULL','$fname','$email','$pass','$phone','$location','$gender',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')";
$result = $conn->query($qry);
echo "<script type = \"text/javascript\">
alert(\"Successfully Registered. Proceed to Login.\");
window.location = (\"account.php\")
</script>";
}
}
I just need it to check if the username (email address) is stored and return that the username is already taken or if not already taken to insert the data into the database.
your're displaying the error if the email is not used (there's no user with this email)
if (mysqli_num_rows($res_e) == 0) {
Thanks for the comments, I noticed that I had a line of code missing:
$rws = $res_e->fetch_assoc();
And I changed the if statement to:
if ($rws == FALSE )
This has resolved my question.
Thanks again.
I am trying to add data into MySQL database through spinner that has several options to choose. I do not know how to state value from spinner into MySQL code. The error occurs on the 39th line, which first line of Inserting Into database using MySQL code. I look forward to hearing from you soon.
<?php
include 'db.php';
$user_type = ['user_type'];
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if(/*$user_type == '' ||*/ $first == '' || $last == '' || $email == '' || $username == '' || $password == '' || $phone == '')
{
echo 'Please, fill all fields';
} else{
$sql = "SELECT * FROM users WHERE user_username='$username'";
$check = mysqli_fetch_array(mysqli_query($conn,$sql));
if(isset($check))
{
echo 'Username already exist. Please, use another one.';
}else{
$hashedPWD = password_hash($password , PASSWORD_DEFAULT); //hash password
$sql = "INSERT INTO users (user_type, user_first, user_last, user_email, user_username, user_pwd, user_phonenumber) VALUES('$user_type','$first','$last','$email','$username','$hashedPWD','$phone')";
if(mysqli_query($conn,$sql))
{
echo 'Successfully registered';
} else{
echo 'Oops! Please try again!';
}
}
mysqli_close($conn);
}
The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}
I've tried things like setting a $var to the MySQL information (such as name or password), then pulling it with PHP, but I cannot figure the PHP out to do so. I use the server connect code as well. I have checked ASP.net out, but don't find any information on altering HTML text to equal SQL information. How might I go about accomplishing this?
One example: The account balance on my website is displayed in the bottom right corner, but I need to pull the balance from a column of my table from my database. What code would I use to set that paragraph element to the server value of account_balance?
My PHP/SQL for Registration:
<?php
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$email = $_POST['email'];
$emailConfirm = $_POST['confirmemail'];
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmpassword'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countryCode = $_POST['countrycode'];
$phoneNumber = $_POST['phone'];
$address = $_POST['address'];
$zipCode = $_POST['zipcode'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$dateOfBirth = $_POST['birthdate'];
$registerDate = "CURDATE()";
$registerTime = "CURTIME()";
$paymentMethod = $_POST['moneymethod'];
if($email == $emailConfirm && $password == $passwordConfirm){
if(!empty($email) && !empty($_POST['confirmemail']) && !empty($password) && !empty($_POST['confirmpassword']) && !empty($fname) && !empty($lname) && !empty($countryCode) && !empty($phoneNumber) && !empty($address) && !empty($zipCode) && !empty($city) && !empty($state) && !empty($country) && !empty($paymentMethod)){
$query = "INSERT INTO user_information (email,password,f_name,l_name,country_code,phone_number,address,city,state,zip_code,country,money_option,join_date,join_time) VALUES ('$email','$password','$fname','$lname','$countryCode','$phoneNumber','$address','$city','$state','$zipCode','$country','$paymentMethod','$registerDate','$registerTime')";
$data = mysql_query ($query)or die(mysql_error());
if($data){
header( 'Location: http://www.madmater.com/register/success.php' );
}else{
echo "Unknown Error!";
}
}else{
echo 'Please fill out all required fields before completing your registration!';
}
}else{
echo 'Your passwords or emails do not match!';
}
?>
I have only tried a simple PHP command, as it is the only thing I could think of, being new to MySQL.
$fname = $_POST['fname']; //From form
echo "<script type="text/javascript">document.getElementById("fname-holder").innerHTML($fname);</script>";
Even a hint of where to start would help, and thank you in advanced.
Since I don't know which row your account balance is called, I've used account_balance as an example in order to get you started.
Here is a basic method to retrieve information from your database:
$fname = stripslashes($_POST['fname']);
$fname = mysql_real_escape_string($_POST['fname']);
// or if DB connnection is required
// $fname = mysql_real_escape_string($_POST['fname'], $db);
$query = "SELECT * FROM user_information WHERE f_name = '$fname'";
while($row = mysql_fetch_array($query)){
$user = $row['f_name'];
$balance = $row['account_balance'];
echo "Username: " . $user;
echo "<br>";
echo "Balance: " . $balance;
}
or mysql_fetch_assoc() depending on what method you wish to use.
For more information on MySQL's SELECT, visit:
http://dev.mysql.com/doc/refman/5.0/en/select.html
You can also try:
$row = mysql_fetch_array($query);
foreach($row as $r) {
echo $r . "<br>";
}
or:
$row = mysql_fetch_assoc($query);
foreach($row as $r) {
echo $r . "<br>";
}
Footnotes:
I have to state that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
There is no sql code in this example. Besides the error i found in this code of PHP for ' is not used.
$fName = $_POST['fname'] //This is from my register form
echo "<script type='text/javascript'>document.getElementById('fname-field').innerHTML(".$fname.");</script>";
and try to give some insert/update code also.
Use form submit your values,
In that form in action give register.php
echo "<pre>";
print_r($_post);
echo"</pre>;
use that you got value
then $name= $_post['name']
$query = "INSERT INTO "Tablename" set name= '".$name."',addeddate=now();
This way you can write.
I have a 'registration' page in PHP and I would like the script to run when an HTML button is clicked.
The PHP basically checks if all fields are filled, checks if the password and email confirmations are the same and saves to the database.
This is the code:
<?php
$Name = isset($_POST['Name']);
$Surname = isset($_POST['Surname']);
$Username = isset($_POST['Username']);
$Email = isset($_POST['Email']);
$C_Email = isset($_POST['C_Email']);
$Password = isset($_POST['password']);
$C_Password = isset($_POST['c_password']);
$SecQ = isset($_POST['SecQ']);
$SecA = isset($_POST['SecA']);
$con = mysql_connect('localhost', 'admin', 'storefile1234');
mysql_select_db ("storefile");
$check_username = mysql_query("SELECT FROM users WHERE username = '$Username'");
$check_email = mysql_query("SELECT FROM users WHERE Email = '$Email'");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if ($Name == null || $Surname== null || $Username == null || $Password == null || $C_Password == null || $Email == null || $C_Email == null || $SecQ == null || $SecA == null ) {
echo "Missing details. Please enter all fields.";
} else {
if(mysql_num_rows($check_username) != 0 && mysql_num_rows($check_email) != 0)
{
echo "Username/Email already exists";
}
if ($Email == $C_Email && $Password == $C_Password) {
$query = "INSERT INTO users (Username, Name,Surname, Password, Email, SecQ, SecA) VALUES ('NULL', ".$Username."', ".$Name."', ".$Surname."', ".$Password."', ".$SecQ."', ".$SecA."', ".$Email.')"';
mysql_query($query) or die ('Error registering.');
echo "Greetings, ".$Name.", you have been registered. ";
} else {
echo "Error registering your account. Please try again.";
}
}
?>
Also, is it recommended?
Whenever I run this page Missing details. Please enter all fields. displays, without having entered any details.
How do you do this?
You tying to get values by isset($_POST['Username']); and like this functions...
But documentation says: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
So check on true, nut null. And escape your POST data after.
You can do like this:
$Name = isset($_POST['Name']) ? mysql_real_escape_string($_POST['Name']) : null;
P.S. Please again. Do not use mysql_* function. They are DEPRECATED.
Look on PDO (or mysqli_*)
For the issue of printing that message when you first load the page, use the array_key_exists function to test if the user has already submited something before checking if any field is null. Something like this:
if (array_key_exists('Name', $_POST) || array_key_exists('Surname', $_POST) || ... )
if ($Name == null || $Surname== null || ... )
echo "Missing details. Please enter all fields.";
Observation: you cannot use the isset function for the same purpose since, according to php documentation, it "determine if a variable is set and is not NULL"
You misuse isset
Try something like this:
$Name = null;
if (isset($_POST['Name'])) {
$Name = $_POST['Name'];
}
isset is only to check if a value is set.