I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....
Related
There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.
Below is my source code:
if(isset($_POST['btnClick']) {
$f_name = NULL;
$l_name = NULL;
$username = NULL;
$email = NULL;
$gender = NULL;
$dob = NULL;
$f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
$l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
$dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);
try {
if(isset($username) && $username != $_SESSION['username']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "Username changed value inputted";
}
else if(isset($email) && $email != $_SESSION['email']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "email change value inputted";
}
else if(isset($username) && isset($email)) {
/*Update both records */
}
You can do something like this:
<?php
try {
if (isset($username) && $username != $_SESSION['username']) {
$fieldsToUpdate[] = 'username=:username';
$updatedFields[] = 'Username';
}
if (isset($email) && $email != $_SESSION['email']) {
$fieldsToUpdate[] = 'email=:email';
$updatedFields[] = 'Email';
}
if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
$sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
/*Update code here...*/
$finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
}
}
PS: This is an example code that how can you optimize your code with PHP arrays and implode() function to run single query to update single or multiple fields.
When I run this page, everything shows up correctly, but then when I try to test my various error messages, my button keeps redirecting me back to my login page as if everything was inputted correctly. It fails to register the if blocks I've included. Below is the php (the html runs fine, not included).
*Side note, a few lines are commented out because I initially had PDO and am changing them over to mysql, but those shouldn't affect everything else running. I have them commented out too so if things did work, I wasn't adding unnecessary info to my database.
Of course, PHP is not skipping anything. It is diligently running your conditions, but in your code the only condition that affects the insert is the last one.
To make it work as desired you have to change all your ifs to elseif save for the first one
The problem: Your error may be set, but your INSERT will execute only if $password == $password2 which will be true if they're both empty.
You need to indicate alternative paths by doing else if
<?php
error_reporting (E_ALL);
$error = "";
if (isset($_POST['createAccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$city = $_POST['city'];
$province = $_POST['province'];
$postalCode = $_POST['postalCode'];
if (!$username){
$error = "<br><div><em>No username entered.</em></div>";
}
elseif (!$password || !$password2){
$error = "<br><div><em>Missing password.</em></div>";
}
elseif (!$firstName || !$lastName){
$error = "<br><div><em>Please enter first and last name.</em></div>";
}
elseif (!$address || !$city || !$province || !$postalCode){
$error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
}
elseif ($password != $password2){
$error = "<br><div><em>Passwords do not match.</em></div>";
}
else{
$conn = mysql_connect(<blocked out for privacy reasons>);
$db = mysql_select_db("grocery", $conn);
$account = mysql_query("SELECT *
FROM accounts
WHERE username = '$username'",
$conn);
$rowExist = mysql_num_rows($account);
if ($rowExist == 1){
$error = "<br><div><em>Username already exists.</em></div>";
}
else {
//$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
// VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
//$conn->exec($newAccount);
header("location: GroceryLogin.php");
}
mysql_close($conn);
}
}
// I'm guessing here you do an echo $error;
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";
?>
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.
Having some issues learning prepaired statments for mysql.
I hade everything working then i got a new problem, The initial problem was i wanted to skip over empty strings in a mysql update form (ie: user profile).
I tried to programaticly do it in php, but i dont understand prepaired statments enough to do this, i keep reading but i am having no success can you help me in making this work as intended? Essentialy im trying to use a array in a prepaired statment.
if (empty($email) && empty($fullname) && empty($address) && empty($country) && empty($state) && empty($city) && empty($postcode) && empty($phone) && empty($password) && empty($random_salt)) {
echo "Nothing to do....";
return;
}
else {
$state = $_POST['state'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$fullname = $_POST['fullname'];
$address = $_POST['address'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$merchantID = $_POST['merchantId'];
// The hashed password from the form
$password = $_POST['p'];
$pass2 = $password;
$pass = $_POST['password'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
$updates = array();
if (!empty($email))
$updates[] = 'email="'.$email.'"';
if (!empty($address))
$updates[] = 'address="'.$address.'"';
if (!empty($country))
$updates[] = 'country="'.$country.'"';
if (!empty($state))
$updates[] = 'state="'.$state.'"';
if (!empty($city))
$updates[] = 'city="'.$city.'"';
if (!empty($postcode))
$updates[] = 'postcode="'.$postcode.'"';
if (!empty($phone))
$updates[] = 'phone="'.$phone.'"';
if (!empty($password))
$updates[] = 'password="'.$password.'"';
if (!empty($random_salt))
$updates[] = 'salt="'.$random_salt.'"';
$updates = implode(', ', $updates);
if ($update_stmt = $mysqli->prepare("UPDATE table SET ? WHERE id = ".$merchantID)) {
$update_stmt->execute($updates);
$update_stmt->close();
//
echo '<br><p>';
echo ' Account infomation update was a success...';
}
else {
echo "oppps, update didnt work, please report this to admin";
}
}
Now i think i have strayed, no matter why i try i cant seem to work out how to do this, granted i dont fully understand prepaired statments im trying.