Hi I have a form where a teacher can create a new school as a user and that teacher's school gets an ID. So I check the database to make sure the id doesn't already exist in the "school" table. If it does I get that school ID so the teacher can create a profile with it. If it doesn't already exist then a new one is created and entered into both the "school" table AND the "users" table for that teacher's school.
It's working fine, only except that every time the form is filled out the data is entered twice, but only in the "USERS" table. In the "school" table it is entered once as it should be.
Can someone tell me why this is happening? I have been looking for weeks.
code:
if(isset($_POST['submit'])){
$name=$_POST['name'];
$name = mysqli_real_escape_string($con,$name);
$lastname=$_POST['lastname'];
$lastname = mysqli_real_escape_string($con,$lastname);
$email=$_POST['email'];
$email = mysqli_real_escape_string($con,$email);
$phone=$_POST['phone'];
$phone = mysqli_real_escape_string($con,$phone);
$school=$_POST['school'];
$school = mysqli_real_escape_string($con,$school);
$address=$_POST['address'];
$address = mysqli_real_escape_string($con,$address);
$region=$_POST['region'];
$region = mysqli_real_escape_string($con,$region);
$state=$_POST['state'];
$state = mysqli_real_escape_string($con,$state);
$zip = $_POST['zip'];
$zip = mysqli_real_escape_string($con,$zip);
$password= $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
//GET STATE NAME
$getState = "SELECT state from `states` WHERE id= '$state'";
$stateRes = mysqli_query($con, $getState);
$stateRow = mysqli_fetch_array($stateRes);
$stateName = $stateRow['state'];
//CHECK SCHOOL
$checkSchool = "SELECT school from `schools` WHERE school= '$school'";
$schoolRes = mysqli_query($con, $checkSchool);
$schoolCount = mysqli_num_rows($schoolRes);
if($schoolCount >0){
//if school exist get it's id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}else{
//if doesn't exist insert new school
$schoolquery = "INSERT INTO schools (state_id, school) VALUES ('$state','$school')";
$schoolresult = mysqli_query($con, $schoolquery);
//get new school id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}
//CHECK USER
$checkUser = "SELECT email from `Users` WHERE email= '$email'";
$userRes = mysqli_query($con, $checkUser);
$userCount = mysqli_num_rows($userRes);
if($userCount >0){
$submitted = "Email is not available";
$invalid = '<input id="email" type="text" name="email" class="form-control is-invalid" required="required" data-error="email is required." data-remote="/validate">';
} else{
$userId = rand(1,9999999);
$check_userId ="select count(*) count from Users where user_id = " . $userId;
while ($row['count'] > 0);
$query = "INSERT INTO Users (id, user_type, name, lastname, email, phone, school, address, state, zip, password, status) VALUES ('$userId','teacher','$name', '$lastname', '$email', '$phone', '$schoolId', '$address', '$stateName', '$zip', '$hash', 'active')";
$result = mysqli_query($con, $query);
if(!$result = $con->query($query)){
die('there was an error running query [' . $con->error . ']');
}else {
header("location: thankyou");
}
}
}
It seems some old artefacts of earlier programming survived:
Maybe this is the new query:
$result = mysqli_query($con, $query);
And maybe this is the old one?
if(!$result = $con->query($query))
Should do the same and be the cause for the duplicate of the insert.
Related
I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}
I have three files reg_form.php, dbconnection.php and insert.php.
When submitting the form the data is not inserted into the database. I can't figure out why. Initially I didn't know how to use insert into multiple tables but took the advice of many posts from here. Unfortunately I have still failed to make it work and it is driving me insane. Here is the sql code so far for the insert.
<?php
include ("dbconnection.php");
if(file_exists("dbconnection.php")) {
echo"Connected to database successfully";
} else if(!file_exists("dbconnection.php")){
echo "Connection failed";
}
$forename = "forename";
$surname = "surname";
$address_line1 = "address_line1";
$address_line2 = "address_line2";
$address_line3 = "address_line3";
$city = "city";
$postcode = "postcode";
$phone = "phone";
$email = "email";
$username = "username";
$password = "password";
$cpassword = "cpassword ";
$query = "INSERT INTO users (username,
password)VALUES('$username','$password');";
$query2 = "INSERT INTO users_details (forename, surname,address_line1,
address_line2, address_line3, city, postcode, phone, email)
VALUES('$forename','$surname','$address_line1','$address_line2',
'$address_line3','$city','$postcode','$phone','$email')";
query ($dbconnection,$sql);
?>
Ok problem is solved. I made a stored procedure because I am doing an INSERT INTO multiple tables and then called it like this.
$sql ="CALL add_user('".$username."', '".$password."', 'user',
'".$forename."','".$surname."', '".$address_line1."' ,
'".$address_line2."', '".$address_line3."', '".$city."', '".$postcode."',
'".$phone."', '".$email."','".is_bool($email_contact)."',
'".is_bool($phone_contact)."')";
$query = $con->prepare($sql);
$query->execute();
I have a form which retrieves various values from my database and displays it in a form. The form contains text boxes, radio, drop down menus. The retrieving part works perfectly and the correct values are displayed for each field. But then when I want to change the field and update the data, it's not updating. Can some please help me with this. Here is my code:
if(isset($_POST['submit'])){
$sql = "UPDATE tbl_dealer_info ";
$sql .= "SET phone = '$phone', email = '$email', sfid = '$sfid', ... WHERE id = '$idhidden' ";
$result = mysqli_query($conn, $sql);
if(!$result){
die('Could not update data: '. mysqli_error());
}
else{
echo "Updated Successfully";
}
}
<input type = "hidden" name = "idhidden" id = "idhidden" value = "" /> // My hidden input to store the id
It displays "Updated Successfully" but isn't actually updating.
Try this
if(isset($_POST['submit'])){
$sql = "UPDATE tbl_dealer_info SET phone = '".$phone."', email = '".$email."', sfid = '".$sfid."', ... WHERE id = ".$idhidden;
$result = mysqli_query($conn, $sql);
if(!$result){
die('Could not update data: '. mysqli_error());
} else{
echo "Updated Successfully";
}
}
you are missing where condition and ';' in the sql statement
$sql = "UPDATE tbl_dealer_info ";
$sql .= "SET phone = '$phone', email = '$email', sfid = '$sfid' WHERE #here where condition #here ";
How can I convert my PHP/Mysql code to PHP/Oracle.
this is my code.
$query = "SELECT name FROM employee WHERE name = '".$userName."' and email = '".$userMobile."' and salary = '".$userSalary."' and deductions = '".$userDeductions."'";
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$existName = $recResult["name"];
if($existName=="") {
$insertTable= mysql_query("insert into employee (name, email, salary, deductions) values('".$userName."', '".$userMobile."', '".$userSalary."', '".$userDeductions."');");
PDO could be one solution. But if you want to continue with the existing, then whats the problem you are getting ?, seems like simple syntax to me. but since PDO is a very good/DB independent way of doing this and hence iam suggesting, You can find an example at http://php.net/manual/en/ref.pdo-oci.php.
Btw, this is a rough thing i could make ( didn't get to test it ), please check it. and more information can be found at selecting record from oracle
$query = "SELECT name FROM employee WHERE name = '".$userName."' and email = '".$userMobile."' and salary = '".$userSalary."' and deductions = '".$userDeductions."'";
$sql = oci_parse($conn,$query);
oci_execute($sql);
$existName = oci_result($sql, 1);
if($existName=="") {
#...
}
I'm trying to do an update without replace the empty fields, for examplo, if i have field number 1 and it is empty nothing happens in database but if field number 2 has some content i want it to be updated. the thing happens is when i do it the empty field goes to the database and REPLACE the content of the field for an empty value.
I need an example of how can i do it.
PD: I am using PHP OOP.
This is my query:
$conio = "UPDATE affiliates SET nickname = '$nickname', fullname = '$fullname' , email = '$email', skype = '$skype', country = '$country', address = '$address', city = '$city', zip = '$zip', bankname = '$bankname', bankaccount = '$bankaccount', beneficiary = '$beneficiary', username = '$username', password = '$password', whene = '$whene' WHERE id = '$users'";
mysqli_query($this->link, $conio) or die (mysqli_error($this->link));
Example: If you want to update the input where the value is not null.
<?php
...
$sql = "UPDATE affiliates SET ";
$sql_where = "WHERE id = '$users'";
$sql_set = "";
$firstName = $_POST['firstName'];
if(!empty($firstName))
$sql_set .= "firstName = '$firstName',";
$lastName = $_POST['lastName'];
if(!empty($lastName))
$sql_set .= "lastName = '$lastName',";
and the same thing for all the other inputs ...
...
mysql_query($sql.$sql_set.$sql_where);
Of course there are better ways of writing this code (ex: using for loop on elements of $_POST), but that's the concept, ...