I am having a problem of syntax my code correctly and i would like some help. I would like to use an if statement and if isset with multiple variables. My existing code is this.
$album_name = $_POST['album_name'];
$img = $_POST['image'];
$artist = $_POST['artist'];
$company = $_POST['company'];
$genre = $_POST['genre'];
$price = $_POST['price'];
$buy_now = $_POST['buy_now'];
if($album_name !='') && if (isset($artist, $company, $price, $buy_now)){
$sql = mysql_query ("INSERT INTO top_albums_info (album_name, image, artist,company,genre,price,buy_now) VALUES ('$album_name','$img','$artist','$company','$genre','$price','".$buy_now."') ");
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=list">';
}else{
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=add&msg=empty">';
}
?>
How can i combine them?
Thanks.
Personally, I handle form submissions completely differently.
BUT, given the structure you have provided, I would recommend doing things a bit differently for ease:
// create a list of fields to check in an array
$fields = array(
'album_name',
'image',
'artist',
'company',
'price',
'buy_now'
);
// iterate over the fields defined in your array
foreach ($fields AS $field) {
// assign the value to the variable ONLY IF the $_POST is set, otherwise empty string
${$field} = (isset($_POST[$field])) ? $_POST[$field] : '';
}
// Now you KNOW its set, so you just check if the field "is"
if ($album_name && $image && $artist && $company && $price && $buy_now) {
// Do stuff. Form submitted and complete
} else {
// Do other stuff. Form not submitted or incomplete
}
When you write `if ($album)`, it's essentially the same as `if ($album != '')`
Change this line
if($album_name !='') && if (isset($artist, $company, $price, $buy_now)){
to
if ($album_name!='' && isset($artist, $company, $price, $buy_now)) {
Change the line to
if (isset($artist, $company, $price, $buy_now)){
if($album_name !=''){
}
}
This will work for sure
Try to use like:
$album_name = $_POST['album_name'];
$img = $_POST['image'];
$artist = $_POST['artist'];
$company = $_POST['company'];
$genre = $_POST['genre'];
$price = $_POST['price'];
$buy_now = $_POST['buy_now'];
if(!empty($album_name) && isset($album_name,$artist,$company,$price,$buy_now)){
$sql = mysql_query ("INSERT INTO top_albums_info (album_name, image, artist,company,genre,price,buy_now) VALUES ('$album_name','$img','$artist','$company','$genre','$price','".$buy_now."') ");
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=list">';
}else{
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=add&msg=empty">';
}
For more detail about isset(): http://php.net/manual/en/function.isset.php
Related
I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?
I'm using a fetchAll and a for loop to do the trick. In the if statement with $validate as result I tried numbers, boolean and now strings to get the result. Nothing worked so far. Here is my code:
$groep_naam = $_POST['groep'];
$naam = $_POST['naam'];
$adres = $_POST['adres'];
$mail2 = $_POST['mail2'];
$pass1 = md5($_POST['pass1']);
$pass2 = md5($_POST['pass2']);
$select = $db->prepare("SELECT * FROM deelnemers");
$select->execute();
$result = $select->fetchAll();
$len = count($result);
for ($x=0;$x<$len;$x++) {
$mail1 = $_POST['mail1'];
$db_mail = $result[$x][mail];
if ($db_mail != $mail1) {
$validate = "true";
}
if ($db_mail == $mail1) {
$validate = "false";
}
}
if (isset($_POST['submit'])) {
if ($mail1 == $mail2 && $pass1 == $pass2) {
if ($validate == "true") {
$add = $db->prepare("INSERT INTO deelnemers (groep_naam, naam, adres, mail, pass, rechten) VALUES ('$groep_naam', '$naam', '$adres', '$mail1', '$pass1', 'user')");
$add->execute();
} if ($validate == "false") {
echo '
<script>
$("#duplicateEntry").modal("show");
</script>
';
}
You are doing it wrong. Instead of fetching all emails, you should do a query to check if that particular email exists in db.
Pseudocode:
$select = $db->prepare("SELECT 1 FROM deelnemers WHERE mail = :email");
$select->bindValue(':email', $_POST['mail1']);
$select->execute();
$validate = $select->rowCount() > 0; //rowCount/rowExists/whatever to check if the query returned anything
Looking at your current code, probable mistake is on line
$db_mail = $result[$x][mail];
It probably should've been
$db_mail = $result[$x]['mail'];
Another thing, you loop through all emails comparing them with the one from request, so even if you find the one email matching it, later in another loop you rewrite your $validate value.
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}
require_once('mysqli_connect.php');
$errors = array();
if(empty($_POST['senFirstName']) && empty($_POST['senLastName'])
&& empty($_POST['recFirstName']) && empty($_POST['recLastName'])
&& empty($_POST['proName']) && empty($_POST['proWeight'])
&& empty($_POST['traNo']) && empty($_POST['shipDate'])
&& empty($_POST['deliDate'])) {
$errors[] = 'Please make sure you type in all the information.';
}
else {
$sfn = mysqli_real_escape_string($dbc, trim($_POST['senFirstName']));
$sln = mysqli_real_escape_string($dbc, trim($_POST['senLastName']));
$rfn = mysqli_real_escape_string($dbc, trim($_POST['recFirstName']));
$rln = mysqli_real_escape_string($dbc, trim($_POST['recLastName']));
$pn = mysqli_real_escape_string($dbc, trim($_POST['proName']));
$pw = mysqli_real_escape_string($dbc, trim($_POST['proWeight']));
$traNo = mysqli_real_escape_string($dbc, trim($_POST['traNo']));
$shipDate = mysqli_real_escape_string($dbc, trim($_POST['shipDate']));
$deliDate = mysqli_real_escape_string($dbc, trim($_POST['deliDate']));
$status = mysqli_real_escape_string($dbc, trim($_POST['status']));
$shiptype = mysqli_real_escape_string($dbc, trim($_POST['shiptype']));
}
if(empty($errors)) { // If everything's OK.
$query = "SELECT traNo, CONCAT(recFirstName, ' ', recLastName) AS recieverName, proName, CONCAT(senFirstName, ' ', senLastName) AS senderName, status, shiptype FROM tracking, rel_tracking_reciever, reciever, product, sender
WHERE traNo='$traNo' AND tracking.traId = rel_tracking_reciever.traId AND reciever.recId = rel_tracking_reciever.recId AND tracking.proId = product.proId AND tracking.senId = sender.senId";
$result = #mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num) { // tracking number was found
while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) {
echo '<div id="error">';
echo "<p>This tracking number <b>{$row['traNo']}</b> has already been assigned to <b>{$row['senderName']}</b></p>\n";
echo '</div>';
}
mysqli_free_result ($result); // Free up the resources.
}
1) I want to validate input box with the multiple IF conditions using && Logical expression but instead, it submits empty forms into the database.
Note: I purposely left out the shipment and status input box because the options cannot be empty by default.
2) Is there a way i can generate the tracking number automatically without typing it manually. I have tried GUID but am not getting it.
Thanks..
You have to set ids that you want to validate - there is no complain.
You can do this with:
$ids = array('senFirstName', 'senLastName', 'recFirstName', 'recLastName' /* ... and more */);
$valid = true;
foreach ( $ids as $id ) {
if ( empty($_POST[$id]) ) {
$valid = false;
}
}
if ( $valid === true ) {
// everything's ok
} else {
$errors[] = 'Please make sure you type in all the information.';
}
You need ||, not && if you want to test, if one is empty.
Otherwise you would proove, if all of them are empty.
(Sorry for bad english)
if(empty($_POST['senFirstName']) || empty($_POST['senLastName']) ...
This starts when a user fills out a form with optional inputs. The values are passed by AJAX to another PHP page to insert into a database. If a particular input is empty, I don't want to update the data stored in the database. Is there a way to check, besides writing lots of if statements, to see if an input value is empty? If it is empty, how can I write the statement so MySQL won't update the corresponding field in the database?
if(isset($_POST['f_name']) && isset($_POST['m_name']) && isset($_POST['l_name']) && isset($_POST['alt_name'])){
$fname = $_POST['f_name'];
$mname = $_POST['m_name'];
$lname = $_POST['l_name'];
$altname = $_POST['alt_name'];
If some of the $_POST entries are empty, then they shouldn't be put into the database. I'm saying this because if there's already an existing value in the database, I don't want to overwrite the value with an empty one.
In this case you also don't allow people to enter just a blank space / &bnsp;
<?php
$empty = FALSE;
foreach ($_POST as $key)
{
if (!isset($key) || strlen(trim($key)) != 0)
{
$empty = TRUE;
}
}
if (!$empty)
{
$fname = $_POST['f_name'];
$mname = $_POST['m_name'];
$lname = $_POST['l_name'];
$altname = $_POST['alt_name'];
}
?>
well...you could use foreach to check all the values.
$empty = FALSE;
foreach ($_POST as $key) {
if (!isset($key)) {
$empty = TRUE;
break;
}
}
if (!$empty) {
$fname = $_POST['f_name'];
$mname = $_POST['m_name'];
$lname = $_POST['l_name'];
$altname = $_POST['alt_name'];
}
I usually use shorthand if statments (also known as the ternary operator) to do something like this. You might be able to write your SQL query something like this:
$query = "UPDATE my_table SET f_name = ".(!empty($fname) ? "'$fname'" : 'f_name').", m_name = ".(!empty($mname) ? "'$mname'" : 'm_name').", ";
//etc.. etc..