PHP - Prepared Statment Update - Dont Include Blank Fields
HI, I have a user form on a modal. The user can be updated from this modal but on the second tab is where the users password can be updated. The update button commits all changes including the password update. If the New Password field is blank i do not want it to be updated. I am using a prepared statement and am not sure how to ommit a field if it is blank. In actual fact there is a new password and a confirm password field which must be the same before the password field is updated. if ($_SERVER['REQUEST_METHOD']=='POST'){ $uid = $_POST['UM-uid']; $fname = $_POST['UM-firstName']; $lname = $_POST['UM-lastName']; $email = $_POST['UM-emailAddress']; $accountlevel = $_POST['UM-accountLevelId']; $mobile = $_POST['UM-mobileNumber']; $roleid = $_POST['UM-roleId']; $newpass = password_hash($_POST['UM-pass'], PASSWORD_DEFAULT); if(!empty($_POST['UM-firstName'])){ // prepare stmt $stmt = $conn->prepare(" UPDATE ssm_user SET user_password=?, user_email=?, user_firstname=?, user_lastname=?, user_account_level_id=?, user_mobile=?, user_role_id=? WHERE user_id = ? "); $stmt->bind_param('sssssssi', $newpass, $email, $fname, $lname, $accountlevel, $mobile, $roleid, $uid); $stmt->execute(); $_SESSION['user']=$fname." ".$lname; $_SESSION['updateUser']="has been successfully updated"; $_SESSION['actionstatus']="success"; I am sure i will be able to work out the password confirmation part, its just the omitting password from being part of the update if blank. Similar TutorialsAs expected when a die statement is triggered, my script is exited and ALL of the fields that have been filled in on my form are wiped clean. This however is proving to be annoying for users making mistakes. Is there a way to keep the data in the correctly filled in fields, and to just wipe or highlight the incorrectly filled in fields? Code: [Select] <?php function checkPostcode (&$toCheck) { $alpha1 = "[abcdefghijklmnoprstuwyz]"; $alpha2 = "[abcdefghklmnopqrstuvwxy]"; $alpha3 = "[abcdefghjkstuw]"; $alpha4 = "[abehmnprvwxy]"; $alpha5 = "[abdefghjlnpqrstuwxyz]"; $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$'; $pcexp[1] = '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$'; $pcexp[2] = '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$'; $pcexp[3] = '^(gir)(0aa)$'; $pcexp[4] = '^(bfpo)([0-9]{1,4})$'; $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$'; $Postcode = strtolower($toCheck); $Postcode = str_replace (' ', '', $Postcode); $valid = false; foreach ($pcexp as $regexp) { if (ereg($regexp,$Postcode, $matches)) { $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]); $toCheck = ereg_replace ('C\/O', 'c/o ', $toCheck); $valid = true; break; } } if ($valid){return true;} else {return false;}; } if(isset($_POST['submit'])) { $drop = mysql_real_escape_string($_POST['drop_1']); $tier_two = mysql_real_escape_string($_POST['Subtype']); $Name = mysql_real_escape_string($_POST["Name"]); $Phone = mysql_real_escape_string($_POST["Phone"]); $Email = mysql_real_escape_string($_POST["Email"]); $Postcode = mysql_real_escape_string($_POST["Postcode"]); $Website = mysql_real_escape_string($_POST["Website"]); if($Name == '') { die ("<div class=\"form\">You did not complete the name field, please try again</div>"); } elseif ($Phone == '' or (preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $Phone))) { die("<div class=\"form\"> You completed the telephone field incorrectly, please try again</div>"); } elseif ($Email == '' or (!filter_var($Email, FILTER_VALIDATE_EMAIL))) { die("<div class=\"form\"> You completed the Email field incorrectly, please try again</div>"); } elseif ($Postcode == '' or (!checkPostcode($Postcode))) { die("<div class=\"form\"> You did not complete the Postcode field correctly, please try again</div>"); } elseif ($Website == '' or (!preg_match("~^[a-z0-9.-]+\.(com|org|net|edu|co.uk)~i", $Website))) { die("<div class=\"form\">You completed the website field incorrectly, please try again</div>"); } else { echo("<div id=\"formtwo\">Thankyou for submiting your details, you will be added to our directory shortly</div>"); } $query = ("INSERT INTO business (`id`, `Name`, `Type`, `Subtype`, `Phone`, `Email`, `Postcode`, `WebAddress`, `Confirmed`) VALUES ('NULL', '$Name', '$drop', '$tier_two' , '$Phone', '$Email', '$Postcode', '$Website', 'Yes')"); mysql_query($query) or die ( "<br>Query: $query<br>Error: " .mysql_error()); } ?> HI All, I am writing a prepared statement to update some user information. Included in this table are the username and password fields. In this particular form, i dont want the user to have access to this information and have built a form that only shows what i want them to be able to change. The bit that i am not sure about is the prepared statement that i am writing. I am getting a boolean error suggesting that my prepare failed and i think this may be because i have not named every field in the table. To give an idea of the table fields i have pulled this from php my_admin (this is not the sql i am running) UPDATE `ssm_user` SET `user_id`=[value-1],`user_email`=[value-2],`user_password`=[value-3], `user_firstname`=[value-4],`user_lastname`=[value-5],`user_accountlevel`=[value-6], `user_mobile`=[value-7],`user_role`=[value-8],`user_lastlogondate`=[value-9] WHERE 1 my prepared statement is $stmt = $conn->prepare(" UPDATE ssm_user SET user_email=?, user_firstname=?, user_lastname=?, user_accountlevel=?, user_mobile=?, WHERE user_id = ? "); $stmt->bind_param('sssssi', $email, $fname, $lname, $accountlevel, $mobile, $uid); $stmt->execute(); return $stmt->affected_rows; Do i have to declare every field in the table or is there something that i am missing here. I can't get my Updated On timestamp to work in the following query... Code: [Select] // ****************************** // Create Temporary Password. * // ****************************** $tempPass = substr(md5(uniqid(rand(), true)), 3, 10); // Build query. $r = "UPDATE member SET pass=?, updated_on=? WHERE email=? LIMIT 1"; // Prepare statement. $stmt2 = mysqli_prepare($dbc, $r); // Bind variables to query. mysqli_stmt_bind_param($stmt2, 'sss', $tempPass, NOW(), $email); // Execute query. mysqli_stmt_execute($stmt2); I used similar code for an INSERT and it worked fine?! Now sure what is going on here... Debbie <?php //COOKIE CHECKER if (isset($_COOKIE["person"])){ if (filter_var($_COOKIE["person"], FILTER_VALIDATE_INT)){ $user_id = $_COOKIE["person"]; //DATABASE CONNECTION VARIABLES $myserver ="localhost"; $myname = "username"; $mypassword = "password"; $mydb ="dbname"; /*SQL CONNECTION*/ // Create connection $conn = new mysqli($myserver, $myname, $mypassword, $mydb); // Check connection if ($conn->connect_error) { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY> <H1>Decline of the Han - Three Kingdoms</H1>'; die("Connection failed: " . $conn->connect_error); echo '</BODY> </HTML>'; } else { //COUNT USER $cquery = "SELECT COUNT(*) AS usercheck FROM Players WHERE ID = ?"; $cid = $conn->prepare($cquery); $cid->bind_param('i', $user_id); $cid->execute(); $cid->bind_result($usercheck); $cid->fetch(); if ($usercheck ==1){ if (isset($_POST["profile"])){ if(!filter_var($_POST["profile"], FILTER_SANITIZE_STRING)){ echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">Unable to filter bio <a href="biography.php">return</a></P>'; echo '</BODY> </HTML>'; } else { $profile = $_POST["profile"]; $sql = "UPDATE Player_Data SET Bio =? WHERE ID=?"; $q = $conn->prepare($sql); $q->bind_param("si", $profile, $user_id); $q->execute(); echo '<P>Biography altered <a href="biography.php">return</a></P>'; //close connection $conn->close(); } } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">'.$usercheck.' '.$user_id.'</P>'; echo '<P class="error">No such user found!</P>'; //close connection $conn->close(); //foot echo '</BODY> </HTML>'; } //end connection check } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">ERROR invalid cookie!</P>'; echo '</BODY> </HTML>'; } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">No cookie detected!<br><a href="login.php">login</a></P>'; echo '</BODY> </HTML>'; } ?>I have an error in the update, but I am not seeing where I made it. Its annoying because the update won't execute and anything beyond the update isn't visible in the html source code in the browser, so it is likely to be a syntax error, but where? <?php //COOKIE CHECKER if (isset($_COOKIE["person"])){ if (filter_var($_COOKIE["person"], FILTER_VALIDATE_INT)){ $user_id = $_COOKIE["person"]; //DATABASE CONNECTION VARIABLES $myserver ="localhost"; $myname = "username"; $mypassword = "password"; $mydb ="dbname"; /*SQL CONNECTION*/ // Create connection $conn = new mysqli($myserver, $myname, $mypassword, $mydb); // Check connection if ($conn->connect_error) { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY> <H1>Decline of the Han - Three Kingdoms</H1>'; die("Connection failed: " . $conn->connect_error); echo '</BODY> </HTML>'; } else { //COUNT USER $cquery = "SELECT COUNT(*) AS usercheck FROM Players WHERE ID = ?"; $cid = $conn->prepare($cquery); $cid->bind_param('i', $user_id); $cid->execute(); $cid->bind_result($usercheck); $cid->fetch(); if ($usercheck ==1){ if (isset($_POST["profile"])){ if(!filter_var($_POST["profile"], FILTER_SANITIZE_STRING)){ echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">Unable to filter bio <a href="biography.php">return</a></P>'; echo '</BODY> </HTML>'; } else { $profile = $_POST["profile"]; $sql = "UPDATE Player_Data SET Bio =? WHERE ID=?"; $q = $conn->prepare($sql); $q->bind_param("si", $profile, $user_id); $q->execute(); echo '<P>Biography altered <a href="biography.php">return</a></P>'; //close connection $conn->close(); } } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">'.$usercheck.' '.$user_id.'</P>'; echo '<P class="error">No such user found!</P>'; //close connection $conn->close(); //foot echo '</BODY> </HTML>'; } //end connection check } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">ERROR invalid cookie!</P>'; echo '</BODY> </HTML>'; } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">No cookie detected!<br><a href="login.php">login</a></P>'; echo '</BODY> </HTML>'; } ?>I have an error in the update, but I am not seeing where I made it. Its annoying because the update won't execute and anything beyond the update isn't visible in the html source code in the browser, so it is likely to be a syntax error, but where? hi, is there a way to do a check for blank fields before posting to database? dumb users keep adding blank fields. i need to check fields $_POST[company], $_POST[jobNO] and $_POST[staff]. Code: [Select] if(isset($_POST['add'])) { $cname=$_POST[company]; $compid = mysql_query("SELECT * FROM company WHERE company = '$cname'"); while($row4 = mysql_fetch_array($compid)) { $cid=$row4["ID"]; } $query = "INSERT INTO jobno VALUES ( NULL, '$_POST[jobNO]', '$cid' )"; mysql_query($query) or die('Error, insert failed'); $query1 = "INSERT INTO staff VALUES ( NULL, '$_POST[staff]', '$_POST[Y]-$_POST[M]-$_POST[D]', '$_POST[jobNO]' )"; mysql_query($query1) or die('Error, insert failed1'); echo "1 record added"; Hi. I've been doing tutorials all day on checking for blank fields and I have wrote a function to do so. For now I am only checking one field to see if it works. If I miss that field out (first name) It works great and displays the correct error message. Problem I have is if I fill in the whole form and send it I get an Inturnal server error. I will post my code to show you. can anyone see whats going wrong? I have \\ some of the code for now because I my keep it if I cant do this error check. session_start(); $validation_id = strval(time()); if(isset($_POST['submit'])) { $first_name = check_input($_POST['first_name'],"Please enter a first name"); $last_name = check_input($_POST['last_name']); $DOB = check_input($_POST['DOB']); $sex = check_input($_POST['sex']); $email = check_input($_POST['email']); $username = check_input($_POST['username']); $password = check_input($_POST['password']); $agree = check_input($_POST['agreed']); $creation_date = check_input($_POST['creation_date']); $user_type = check_input($_POST['member_type']); $access_level = check_input($_POST['access_level']); $validation = check_input($_POST['validation_id']); $club_user =check_input($_POST['user_type']); // $first_name = mysql_real_escape_string($_POST['first_name']); // $last_name = mysql_real_escape_string($_POST['last_name']); // $DOB = mysql_real_escape_string($_POST['DOB']); // $sex = mysql_real_escape_string($_POST['sex']); // $email = mysql_real_escape_string($_POST['email']); // $username = mysql_real_escape_string($_POST['username']); // $password = mysql_real_escape_string($_POST['password']); // $agree = mysql_real_escape_string($_POST['agreed']); // $creation_date = mysql_real_escape_string($_POST['creation_date']); // $user_type = mysql_real_escape_string($_POST['member_type']); // $access_level = mysql_real_escape_string($_POST['access_level']); // $validation = mysql_real_escape_string($_POST['validation_id']); // $club_user = mysql_real_escape_string($_POST['user_type']); $insert_member= "INSERT INTO Members (`first_name`,`last_name`,`DOB`,`sex`,`email`,`username`,`password`,`agree`,`creation_date`,`usertype`,`access_level`,`validationID`) VALUES ('".$first_name."','".$last_name."','".$DOB."','".$sex."','".$email."','".$username."','".$password."','".$agree."','".$creation_date."','".$user_type."','".$access_level."', '".$validation."')"; $insert_member_now= mysql_query($insert_member) or die(mysql_error()); $url = "thankyou.php?name=".$_POST['username']; header('Location: '.$url); and the form <form method="POST" name="member_accounts" id="member_accounts"> <input name="first_name" type="text" class="form_fields" value="<?php echo $_POST['first_name'];?>" size="20" /> <input name="last_name" type="text" class="form_fields" value="<?php echo $_POST['last_name'];?>" size="20" /> <input name="submit" type="submit" class="join_submit" id="submit_member" value="Create Account" /> <? function check_input($data, $problem='') { $data= trim($data); $data= stripslashes($data); $data= htmlspecialchars($data); if ($problem && strlen($data) ==0) { die($problem); } return $data; } ?> Hello, I'm using the below code to determine whether fields have been left blank, however, it only a standard sentence, i'd like to customise it, like: "Email has been left blank" or The email and message has been left blank. My best preference would be to bullet point each line. IE: Email has been left blank. Message has been left blank. $name = $_POST['name']; $visitor_email = $_POST['email']; $user_message = $_POST['message']; if(empty($name)|| empty($visitor_email)|| empty($user_message)) { $errors .= "\n Some of the above fields have not been filled in.<br><br> "; } Many thanks. Good morning, I am a beginner at PHP, but trying to write a simple script to use at work and currently stuck on one part, looking for some advice! I have a simple form here > http://jmdostal.com/route2.php (Feel free to use it to test), that returns data on the next page, in a format such as : Jose F - Jose A - 285 Brenda L [Delivery] [Dallas] - Items Job 2 [Pickup] [Arlington] - Items [] [] - [] [] - [] [] - [] [] - [] [] - Gustavo - +1 - 284/pickup Jody W [Delivery] [Keller] - Items [] [] - [] [] - [] [] - [] [] - [] [] - [] [] - My question is how can I get it not to show the fields that are empty, so I dont have a bunch of lines with [] [] - formatting Here is my coding you can view here > http://jmdostal.com/code.txt A friend had suggested to me trying to use isset , so I tried it on a few lines, such as : if(isset($_POST['items14'])){ $items14 = "- ". Trim(stripslashes($_POST['items14'])); } But it didnt seem to change anything. Im sure this is something simply, Any suggestions are appreciated! Thanks ! Hi all, I am trying to write a script that finds the blank $_POST values and add them to a $blank_array. All I get is a blank page - any ideas? Also is there some code I can put at the top of every php page to show exactly what the errors are? - I have tried a few scripts but have not found one to work universally. include("cxn.php"); $reg = "G-".strtoupper($_POST['reg']); $sql = "SELECT * FROM sales WHERE reg='$reg'"; $result = mysqli_query($cxn,$sql) or die ("Couldn't execute query"); $num = mysqli_num_rows($result); if ($num >0) // Listing Already Found { echo "The aircraft '$reg' is already listed!"; echo $_SESSION['logname']; } foreach ($_POST as $value) { if ($value == "") { $blank_array[] = $field; } if (@sizeof($blank_array) > 0) // blank fields are found { $error = "Please fill in all the form.<br>"; include ("../sell-your-reg.php"); } } ?> Hi guys! New to the community and hope to learn a lot here! Here is some background info and what I want to do, and what I know. I have been building websites for years, and I am familiar with Actionscript 3.0. And I have successful ran a few wordpress websites. What I am trying to do right now however is modify this form script I found, to only email the data when the field isn't left blank. It's stumping me because the actual "message" that ends up being the body of the email is a variable. And form what I can tell I can't figure out how to put if statements into it. If anyone can take a look at this script and give me any pointers you would be awesome. Code: [Select] <?php //trying to store the date in a separate variable only when it's not blank if ($_POST['starttime'] == '') { //nothing; } else { $showStartTime == "Start time: " . $_POST['starttime'] . ""; } if ($_POST['finishtime'] == '') { //nothing; } else { $showFinishTime == "Finish time: " . $_POST['finishtime'] . ""; } // Read POST request params into global vars $to = $_POST['to']; $from = $_POST['from']; $name = $_POST['name']; $company = $_POST['company']; $newcustomer = $_POST['newcustomer']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $subject = ("Event Rental for " . $name . ""); $description = $_POST['description']; $phone = $_POST['phone']; $message = (" Name: " . $name . " Company or Organization: " . $company . " Phone Number: " . $phone . " Email Address: " . $from . " Street Address: " . $address1 . " " . $address2 . " New Customer: " . $newcustomer . " Customer From: " . $_POST['howyouheard'] . " Interested in: SkyLoft " . $_POST['whichspace'] . " Date: " . $_POST['date'] . " Day of Week: " . $_POST['dayofweek'] . " " . $showStartTime . " " . $showFinishTime . " Number of Guests: " . $_POST['Guests'] . " Format: " . $_POST['format'] . " Occasion: " . $_POST['Occasion'] . " Optional Needs: " . $_POST['dj'] . " " . $_POST['tables'] . " " . $_POST['chairs'] . " " . $_POST['eventbanner'] . " " . $_POST['pasoundsystem'] . " Message: " . $description . " "); // Obtain file upload vars $fileatt = $_FILES['fileatt']['tmp_name']; $fileatt_type = $_FILES['fileatt']['type']; $fileatt_name = $_FILES['fileatt']['name']; $headers = "From: $from"; if (is_uploaded_file($fileatt)) { // Read the file to be attached ('rb' = read binary) $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // Add the headers for a file attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // Add a multipart boundary above the plain message $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; } // Send the message $ok = @mail($to, $subject, $message, $headers); if ($ok) { echo "<p><b>Thank you for your interest in SkyLofts!</b> <br>You should recieve a verification in your inbox that we recieved your request. We will contact you as soon as possible and hopefully be able to answer any questions you may have! You can also contact us via phone 410-791-6699, or toll-free 1-800-344-0410.</p>"; } else { echo "<p>There was an error when processing your request. Please try again.</p>"; } ?> So im trying to figure out if a user is already in the table so im checking for the number of rows where the user id shows up on a record and if its greater then one redirect them. My problem is the if statment does not work and I know there is more then one row. Also die ($row2); wont output data but it will in a sentence (see code below for example) Code: [Select] $sql2 = "SELECT * FROM purchases WHERE nid = '$id' AND uid = '$user_id'"; $res2 =mysql_query($sql2) or die (mysql_error()); $row2 = mysql_num_rows($res2); die($row2);//no output die("There are a total of ".$row2." rows");//outputs There are a total of 20 rows if ($row2 > 0){//if statment doesnt work. //already bought the note header("Location: view.php?error=2"); } I have this code: Code: [Select] if (isset($_POST['update'])){ $ids = implode(",", array_map('intval', $_POST['m'])); $ranks = implode(",", array_map('intval', $_POST['ranks'])); if ($ids < 1) message("Incorrect Data"); if ($ranks < 0) message("Incorrect Data"); echo $ids; echo "<br>"; echo $ranks; exit; $db->query('UPDATE friends set RANKS WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); redirect("s.php?section=Friends","Thanks, Ranks Updated"); } I grab the id's from the rank This will spit out 3,4 for $ids and for $ranks, 1,2 as you can see, set for 1 and 2 respectivaly. My problem is how can I use MYSQL to update the data correspond to each id using a IN clause? Code: [Select] $db->query('UPDATE friends set RANKS = "LOST $RANKS? HERE" WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); I have the following PHP script to update two time/date fields in the database. When i run this the fields are not updated. Can anyone see where i m going wrong. <?php $con = mysql_connect("localhost","dbname","dbpassword"); if (!$con) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db("my_db", $con); mysql_query("UPDATE msm_content SET created = '2011-01-02 00:00:00', modified = '2011-01-01 00:00:00'"); echo 'Query Updated successfully'; mysql_close($con); ?> Your guidance is much appreciated. Now, here's what I'm trying to do:
First, I have a file filled with data like such:
title
tag
1
2
Title
Description
Etc
Next, I upload that file to my site which then proceeds to make an array with said data and then inserts it into my database. But this is not the intended behavior. Right now, if I upload the same file again, it will re-insert everything and duplicate all entries.
What I want to do is check if the data in the file has already been added, do nothing. If it's been modified, I want to update the database where changes have been made and not duplicate anything.
Currently, my code does all that except one thing whre I'm really stuck: it won't update the changes from the file to the database. I've tried echoing everything and it's to be working except for the query so I take it the error is in there but I can't find it... I'm still learning PHP and MySQL so I thought maybe somebody could help indicate where or what I'm doing wrong in the query. Thanks in advance !
Here's my attempt at doing so:
$register_ep_data = array( 'show' => $name, 'season' => $srNum, 'ep' => $epNum, 'app_name' => $epName, 'tag' => $tag, 'app_about' => $desc, 'app_website' => $imdb, 'app_release' => $release, 'type' => $type, 'app_code' => $Frame ); array_walk($register_ep_data, 'array_fu'); $fields = '`' . implode('`, `', array_keys($register_ep_data)) . '`'; $data = '\'' . implode('\', \'', $register_ep_data) . '\''; $epFound = false; $id = 0; while ($ep_list_data = mysql_fetch_array($turtle)) { $id = $ep_list_data['app_id']; $currentNAME = $ep_list_data['app_name']; $SERIES = $ep_list_data['show']; if ($SERIES == $name) { if ($currentNAME == $epName) { $epFound = true; break; } } } if ($epFound) { mysql_query("UPDATE `games` SET ($fields) VALUES ($data) WHERE `app_id` = '$id'"); } else { mysql_query("INSERT INTO `games` ($fields) VALUES ($data)"); }A few explanations: $fields would equal to something like: `show`, `season`, `ep`, etc... and $data to 'example', '1', '2', 'etc' ...added to an error log? Currently, my coding is as follows: Form to gather data: Code: [Select] <html><head><title>Car Accident Report Form</title></head> <form action="errorlog.php" method="post"> First Name: <br><input type="text" name="name"><br> Surname:<br> <input type="text" name="surname"><br> Age: <br><input type="text" name="age"><br> Weeks Since Accident: <br><input type="text" name="weeks"><br> <input type="submit" value="Submit"> </form> Coding for error log: Code: [Select] <html><head><title>Validating Car Accident Report Form Details</title></head> <?php $name=$_POST["name"]; $surname=$_POST["surname"]; $age=$_POST["age"]; $weeks=$_POST["weeks"]; $subtime = strftime('%c'); $pass = "The details uploaded are fine<br><br>"; if ((((trim($name)="" && trim($surname)="" && trim($age)="" && trim($weeks)="")))) { echo "It seems that you have not entered a value for the Name, Surname, Age or Weeks fields. This has been added to the error log.<br><br>"; error_log("<b><u>Error</b></u><br>The user has not entered any values", 3, "C:/xampp/htdocs/errorlog.txt"); } if (($age<18)&& ($weeks<=1)) { echo "It seems that you have entered an invalid age and number of weeks since the accident. This has been added to the error log.<br><br>"; error_log("<b><u>Error</b></u><br>The user has entered an age that is below 18 and the number of weeks since the accident is equal to or under 1 week!<br>Age entered:" . $age . "<br>Number Of Weeks Since Accident entered:" . $weeks . "<br>Time that form was submitted:" . $subtime . "<br><br>", 3, "C:/xampp/htdocs/errorlog.txt"); } else if ($age<18) { echo "It seems that you have entered an invalid age. This has been added to the error log.<br><br>"; error_log("<b><u>Age Error</b></u><br>The user has entered an age that is below 18!<br>Age entered:" . $age . "<br>Time that form was submitted:" . $subtime . "<br><br>", 3, "C:/xampp/htdocs/errorlog.txt"); } else if ($weeks<=1) { echo "It seems that you have entered an invalid age number of weeks since the accident. This has been added to the error log.<br><br>"; error_log("<b><u>Week Error</b></u><br>The user has entered a number of weeks since the accident that is equal to or under 1 week!<br>Number Of Weeks Since Accident entered:" . $weeks . "<br> Time that form was submitted:" . $subtime . "<br><br>", 3, "C:/xampp/htdocs/errorlog.txt"); } else { echo $pass; } echo "Car Accident Report Form details have been sent<br>"; echo "<a href='readlog.php'>Read Error Log</a>" ?> </html> How can I get it so that if a user presses the space bar in a field, then the trim function sees that there's no white space and then this gets added to the error log? Any help is appreciated! Hi I have an update page with multipule drop down menus, I am looking for a way to allow only the drop down menus that have been altered to be sent to the database. One way was to add the following code, where the $type_id equals 0 then add nothing to the database. Code: [Select] if ($type_id == 0) { $type_id = ""; } However I am getting a syntex error with this, if I enter a value into the $type_id it selects that fine. eg. Code: [Select] if ($type_id == 0) { $type_id = "2"; } What is the right way to send nothing to the database? Fuller code of the page is here <?php require_once("includes/sessions.php"); ?> <?php require_once("includes/connections.php"); ?> <?php require_once("includes/functions.php"); ?> <?php confirm_logged_in();?> <?php usersid(); ?> <?php find_selected_event(); find_selected_region(); ?> <?php $selected_event = getevent_byid ($url_eventid); $orgdescrip = orgdescription($url_eventid); $leveldescrip = leveldescription($url_eventid); $typedescrip = typedescription($url_eventid); $champdescrip = champdescription($url_eventid); $disdescrip = disdescription($url_eventid); $venuedescrip = venuedescription($url_eventid); $statusdescrip = statusdescription($url_eventid); ?> <?php if (!isset($new_event)) {$new_event = false;} ?> <?php // make sure the subject id sent is an integer if (intval($_GET['url_eventid']) == 0) { redirect_to('controlpanel.php'); } include_once("includes/form_functions.inc.php"); // START FORM PROCESSING // only execute the form processing if the form has been submitted if (isset($_POST['submit'])) { // initialize an array to hold our errors $errors = array(); // perform validations on the form data $required_fields = array('title'); $errors = array_merge($errors, check_required_fields($required_fields, $_POST)); $required_numberfields = array(); $errors = array_merge($errors, check_number_fields($required_numberfields, $_POST)); $fields_with_lengths = array(); $errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST)); // clean up the form data before putting it in the database $url_eventid = mysql_prep($_GET['url_eventid']); $user_id = mysql_prep($_POST['user_id']); $title = trim(mysql_prep($_POST['title'])); $event_details = mysql_prep($_POST['event_details']); $type_id = mysql_prep($_POST['type_id']); $champ_id = mysql_prep($_POST['champ_id']); $dis_id = mysql_prep($_POST['dis_id']); $org_id = mysql_prep($_POST['org_id']); $venue_id = mysql_prep($_POST['ven_id']); $level_id = mysql_prep($_POST['level_id']); $status_id = mysql_prep($_POST['status_id']); if ($type_id == 0) { $type_id = ""; } // Database submission only proceeds if there were NO errors. if (empty($errors)) { $sql = "UPDATE events SET \n" . "title = '{$title}',\n" . "event_details = '{$event_details}',\n" . "type_id = {$type_id},\n" . "champ_id = {$champ_id},\n" . "dis_id = {$dis_id},\n" . "org_id = {$org_id},\n" . "ven_id = {$venue_id},\n" . "user_id = {$url_userid},\n" . "level_id = {$level_id},\n" . "status_id = {$status_id}\n" . "WHERE event_id = {$url_eventid} \n" . "LIMIT 1"; if ($result = mysql_query($sql, $connection)) { // as is, $message will still be discarded on the redirect $message = "The event was successfully updated."; // get the last id inserted over the current db connection $new_event_id = mysql_insert_id(); redirect_to("newevent.php"); } else { $message = "I am sorry but the event could not be updated."; $message .= "<br />" . mysql_error(); } } else { if (count($errors) == 1) { $message = "There was 1 error in the form."; } else { $message = "There were " . count($errors) . " errors in the form."; } } // END FORM PROCESSING } ?> <?php /*THIS CODE WITH RETURN IN THE BROWSER THE URLS THAT ARE BEING PULLED DOWN*/ if(empty($_GET)) echo "No GET variables"; else print_r($_GET); ?> <?php include("includes/header.inc.php"); ?> <title>Horse Events</title> <?php include_once("includes/meta.inc.php");?> <?php include_once("includes/cssfavgoogle.inc.php");?> <link href="css/adminpanel.css" rel="stylesheet" type="text/css" /> <style> input[type="number"] { width:40px; } </style> </head> <body> <div id="wrapper"> <div id="header"> <img src="images/horseevents_wheretogo.png" align="right" /> <?php require_once ("includes/adminmenu.inc.php"); ?> </div> <div id="adminleft"> <h2>YOUR UPCOMING EVENTS <?php echo "<a href=\"newevent.php?url_userid={$url_userid}\"><img src=\"images/pink/add_event.png\" align=\"right\" width=\"131\" height=\"19\" /></a>" ?></h2> <table id="datetable" width="300" border="0" > <?php $event_users_set = get_upcomingeventsforuser ($url_userid); while ($eventid = mysql_fetch_array ($event_users_set)){ echo"<tr class=\'date\'>"; echo"<td>" . $eventid["stdate"] ."</td>"; echo"<td><a href=\"editevent.php?url_userid={$url_userid}&url_eventid=". urlencode ($eventid['event_id']) . "\">". $eventid ['title'] . "</td>"; echo"</tr></a>"; } ?> </table> <br /> <h2>YOUR PAST EVENTS</h2> <table id="datetable" width="300" border="0" > <?php $event_users_set = get_pasteventsforuser ($url_userid); while ($eventid = mysql_fetch_array ($event_users_set)){ echo"<tr class=\'date\'>"; echo"<td>" . $eventid["stdate"] ."</td>"; echo"<td><a href=\"editevent.php?url_userid={$url_userid}&url_eventid=". urlencode ($eventid['event_id']) . "\">". $eventid ['title'] . "</td>"; echo"</tr></a>"; } ?> </table> </div> <div id="admincontent"> <span class="h1pln">Edit Your Event</span><a class="delete" href="deleteevent.php?url_eventid=<?php echo $url_eventid; ?>" onClick="return confirm('Are you sure you want to delete?')">Delete</a><br /> <span class="h3pln">Please make sure you complete all the compulary fields<span class="compuls">*</span>.<br /> The more accurately you enter your event the more people will be able to then find it. <br /> <br /> If there are any selections we do not currently have available please click here and I will add them to your drop down menus.</span> <?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?> <?php if (!empty($errors)) { display_errors($errors); } ?> <form id="newevent" action="editevent.php?url_eventid=<?php echo urlencode ($selected_event ['event_id']); ?>" method="post"> <table id="neweventdisplay" cellpadding="5" width="400" border="0"> <tr> <td><input type="text" name="event_id" value="<?php echo $url_eventid; ?>" /></td> <td><input type="text" name="user_id" value="<?php echo $url_userid; ?>" /></td> </tr> <tr> <td class="heading">Event Title</td> <td><input id="titleinput" name="title" type="text" value="<?php echo $selected_event ['title']; ?>" /><span class="compuls">*</span><span class="smalltext">Enter up to 36 characters</span></td> </tr> <tr> <td class="heading">Current Status</td> <td><?php echo $statusdescrip ['status_description']; ?> <select name="status_id" > <?php $status_set = findstatus(); $statuslist = mysql_fetch_assoc ($status_set); ?> <?php do { ?> <option value="<?php echo $statuslist ['status_id']; ?>" ><?php echo $statuslist ['status_description']; ?></option> <?php } while ($statuslist = mysql_fetch_assoc ($status_set)); ?></select> <span class="compuls">*</span></td> </tr> <tr> <td class="heading">Organiser</td> <td><?php echo $orgdescrip ['org_name']; ?> <select name="org_id"> <?php $organisers_set = findorganisers(); $orglist = mysql_fetch_assoc ($organisers_set); ?> <?php do { ?> <option value="<?php echo $orglist ['org_id']; ?>" ><?php echo $orglist ['org_name']; ?></option> <?php } while ($orglist = mysql_fetch_assoc ($organisers_set)); ?></select></td> </tr> <tr> <td class="heading">Start Date</td> <td id="dateinput"><?php echo $selected_event ['stdate']; ?></td> </tr> <tr> <td class="heading">Type Of Event</td> <td><?php echo $typedescrip ['type_description']; ?> <select name="type_id"> <?php $type_set = findtype(); $typelist = mysql_fetch_assoc ($type_set); ?> <?php do { ?> <option value="<?php echo $typelist ['type_id']; ?>" ><?php echo $typelist ['type_description'], $typelist ['type_id']; ?></option> <?php } while ($typelist = mysql_fetch_assoc ($type_set)); ?></select><span class="compuls">*</span></td> </tr> <tr> <td class="heading">Venue</td> <td><?php echo $venuedescrip ['ven_name']; ?><select name="ven_id"> <?php $venues_set = findvenues(); $venuelist = mysql_fetch_assoc ($venues_set); ?> <?php do { ?> <option value="<?php echo $venuelist ['ven_id']; ?>" ><?php echo $venuelist ['ven_name'], $venuelist ['ven_id']; ?></option> <?php } while ($venuelist = mysql_fetch_assoc ($venues_set)); ?></select></td> </tr> <tr> <td class="heading">Discipline</td> <td><?php echo $disdescrip ['dis_description']; ?><select name="dis_id"> <?php $discipline_set = finddisciplines(); $dislist = mysql_fetch_assoc ($discipline_set); ?> <?php do { ?> <option value="<?php echo $dislist ['dis_id']; ?>" ><?php echo $dislist ['dis_description'], $dislist ['dis_id']; ?></option> <?php } while ($dislist = mysql_fetch_assoc ($discipline_set)); ?></select><span class="compuls">*</span></td> </tr> <tr> <td class="heading">Level</td> <td><?php echo $leveldescrip ['level_description']; ?> <select name="level_id"> <?php $level_set = findlevels(); $levellist = mysql_fetch_assoc ($level_set); ?> <?php do { ?> <option value="<?php echo $levellist ['level_id']; ?>" ><?php echo $levellist ['level_description'], $levellist ['level_id']; ?></option> <?php } while ($levellist = mysql_fetch_assoc ($level_set)); ?></select></td> </tr> <tr> <td class="heading">Is This A Championship</td> <td><?php echo $champdescrip ['champ_description']; ?><select name="champ_id"> <?php $championship_set = findchampionships(); $champlist = mysql_fetch_assoc ($championship_set); ?> <?php do { ?> <option value="<?php echo $champlist ['champ_id']; ?>" ><?php echo $champlist ['champ_description'], $champlist ['champ_id']; ?></option> <?php } while ($champlist = mysql_fetch_assoc ($championship_set)); ?></select></td> </tr> <tr> <td class="heading">Event Details</td> <td><textarea name="event_details" cols="45" rows="15" ><?php echo $selected_event ['event_details']; ?> </textarea></td> </tr> <tr> <td class="heading">Upload Schedule</td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name="submit" id="convert" value="Update Your Event"></td> </tr> </table> <a class="delete" href="controlpanel.php">Cancel</a> </form> </div> <div id="adminright"> </div> <br clear="all" /> <?php require("includes/lowerlistings.inc.php"); ?> <?php require("includes/footer.inc.php"); ?> </div><!--End of Wrapper--> </body> </html> Hey there fellow PHP coders I am sorta a newbie with php but i am having a heck of a time with this If Else statement and i know someone with experience will be able to tell me why the else if is not working What this is here is on our company intranet our agent love to send out flyers without picture and makes us look bad... so this is an IF Else if there is a picture display the eFlyer options else dont display the flyer options If doesnt seem to do the else can anyone see something that i am not seeing i have been staring at it for 2 hours now trying different little things and havent been able to get it to work PLEASE PLEASE help me thanks for everyone who reads this <?php if( $mlsInfo['PhotoURL'] != "") echo "<a href='emailListing.php?type=rs&mlsn=".$propInfo['MLSNumber']."' target='_blank' onMouseOver='doTooltip(event, 0)' onMouseOut='hideTip()' ><img src='images/buttons/fb_eListing.gif' width='106' height='20' border='0'></a> <a href='emailPostcard.php?type=rs&mlsn=".$propInfo['MLSNumber']."' target='_blank' onMouseOver='doTooltip(event, 2)' onMouseOut='hideTip()' ><img src='images/buttons/fb_ePostcards.gif' width='106' height='20' border='0'></a> <a href='emailFlyer.php?type=rs&mlsn=".$propInfo['MLSNumber']."' target='_blank' onMouseOver='doTooltip(event, 3)' onMouseOut='hideTip()' ><img src='images/buttons/fb_Flyer.gif' width='110' height='20' border='0'></a> <a href='../print_rs.php?type=rs&mlsn=".$propInfo['MLSNumber']."' target='_blank' onMouseOver='doTooltip(event, 5)' onMouseOut='hideTip()' ><img src='images/buttons/fb_printFlyer.gif' width='106' height='20' border='0'></a> <a href='fb_propertyRS_print.php?type=rs&mlsn=".$propInfo['MLSNumber']."' target='_blank' onMouseOver='doTooltip(event, 4)' onMouseOut='hideTip()' ><img src='images/buttons/fb_printListing.gif' width='106' height='20' border='0'></a> "; else echo "You Dont have any photos please add some"; ?> hey guys i have a car dealer script and i want to make the interface look better.. so i want to put icons(door locks-ac-auto-manu-4 door..) my issue is the if.. so im guessing <? if ( $row3['Door_locks'] == 1 ) { echo "<img src="icons/Doors.png" width="32" height="32" border="0">";} ?> im having a few problems with if and endif see line of code below what have i done wrong <? if($forum_user['g_id'] <= USER_MOD):?><th class="tcr"><?php echo $lang_online['IP'] ?></th><?php echo "\n";endif ?> keeps kicking up error: Parse error: syntax error, unexpected T_ENDIF thanks |