I have the following code:
session_start();
$error_fname = $_SESSION['error_fname'];
$error_lname = $_SESSION['error_lname'];
$error_email = $_SESSION['error_email'];
$error_email_invalid = $_SESSION['error_email_invalid'];
$error = array(
'fname' => $error_fname,
'lname' => $error_lname,
'email' => $error_email,
'email_invalid' => $error_email_invalid);
This is on top of the page, and down at my contact form, the following code is placed:
<?php echo $error; ?>
For some reason, when I trigger an error, the page refreshes, and prints out the following:
How can I make it so one variable ($error) displays all of the possible errors?
The _SESSION variables are defined in the following file:
/assets/redir/contact.php
<?php
session_start();
$_SESSION['error_fname'] = " ";
$_SESSION['error_lname'] = " ";
$_SESSION['error_email'] = " ";
$_SESSION['error_email_invalid'] = " ";
if($_POST['fname']){
if($_POST['lname']){
if($_POST['email']){
if (strstr($_POST['email'], '#') && strstr($_POST['email'], '.')) {
mail('', 'Nieuw bericht van je website!', strip_tags($_POST['message']));
header('Location: ../../index.php');
}else
$_SESSION['error_email_invalid'] = "<div class='mssg mssg_error'>Het ingevoerde e-mail adres is niet correct.</div>";header('Location: ../../index.php');
}else
$_SESSION['error_email'] = "<div class='mssg mssg_error'>Je e-mail adres is verplicht</div>";header('Location: ../../index.php');
}else
$_SESSION['error_lname'] = "<div class='mssg mssg_error'>Je achternaam is verplicht</div>";header('Location: ../../index.php');
}else
$_SESSION['error_fname'] = "<div class='mssg mssg_error'>Je voornaam is verplicht</div>";header('Location: ../../index.php');
?>
When using var_dump($error); I get the following:
Thanks in advance!
$error is array so you need to iterate by this and display each element separately:
foreach ($error as $er) {
if (!empty($er)) {
echo $er;
break; //to leave for first error
}
}
Related
I have an input in my code that update a value in MySQL, but is not working, if i set the value manually in PHPMyAdmin, the value display in HTML, but when i try update, return to 0.
I have the same code to do a similar function, and have copied, and it still isn't working.
Controller:
function ordemmobile(){
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if($id > 0){
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if( $this->categorias_model->alterar($data)){
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
echo json_encode(array('status' => $ret , 'msg' => $msg));
}
View:
echo "<td><input type=\"number\" name=\"ordemmobile\" value=\"".$registro->ordemmobile."\" style=\"width:80px; margin:0\" class=\"ordemmobile\" data-id=\"".$registro->id."\" data-url=\"".base_url('adm/'.$this->router->fetch_class().'/ordemmobile')."\" /><span style=\"display:none\">".$registro->ordemmobile."</span></td>";
Model (alterar):
function alterar($data){
$this->db->where('id',$data['id']);
return $this->db->update('ga845_categorias',$data);
}
Looks like it should work if the inputs are getting posted. Checking both inputs would be a good idea.
Consider this
function ordemmobile()
{
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if(empty($id) || empty($ordemmobile))
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
else
{
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if($this->categorias_model->alterar($data))
{
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}
else
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}
echo json_encode(array('status' => $ret, 'msg' => $msg));
}
You should also take a good look at what your browser's Web Developer Tools tell you about the request to and response from the server.
What I'm trying to do is to echo something at the top of the page while it catches something ad the bottom.
This is my script:
<html>
<head>
<title>Westpop</title>
<link rel="stylesheet" href="opmaak.css">
</head>
<body>
<div id="header"></div>
<?php
$host = "localhost";
$gebruikersnaam = "root";
$wachtwoord = "";
mysql_connect($host, $gebruikersnaam, $wachtwoord);
$demooistedatabase = "c5g4westpopintranet";
mysql_select_db($demooistedatabase);
$achternaam = $_POST["achternaam"];
$voornaam = $_POST["voornaam"];
$gbdatum = $_POST["geboortedatum"];
$email = $_POST["email"];
$geslacht = $_POST["geslacht"];
$wachtwoord = $_POST["wachtwoord"];
$woonplaats = $_POST["woonplaats"];
$adres = $_POST["adres"];
$telefoonnummer = $_POST["telefoonnummer"];
$functie = $_POST["functie"];
$achternaam = stripslashes($achternaam);
$voornaam = stripslashes($voornaam);
$gbdatum = stripslashes($gbdatum);
$email = stripslashes($email);
$geslacht = stripslashes($geslacht);
$wachtwoord = stripslashes($wachtwoord);
$woonplaats = stripslashes($woonplaats);
$adres = stripslashes($adres);
$telefoonnummer = stripslashes($telefoonnummer);
$functie = stripslashes($functie);
$query ="INSERT INTO vrijwilliger (voornaam, achternaam, gbdatum, geslacht, wachtwoord, woonplaats, adres, telefoonnummer, functie, activiteitID, groepID, email)
VALUES('$voornaam','$achternaam','$gbdatum','$geslacht','$wachtwoord','$woonplaats','$adres','$telefoonnummer','$functie',null,null,'$email')";
?>
<div id="registreer">
<center>
<br><br>
<?php
$foutloos=true;
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $wachtwoord) === 0)
{
echo '<fblack>Wachtwoord moet minstens 8 tekens lang zijn, een kleine letter, grote letter én cijfer bevatten.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[0-9]{10}+$/", $telefoonnummer) === 0)
{
echo '<fblack>Het telefoonnummer moet 10 cijfers bevatten.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/", $gbdatum) === 0)
{
echo '<fblack>Geboorte datum moet op dit formaat ingevoerd worden: JJJJ-MM-DD<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $email) === 0)
{
echo '<fblack>Email moet hier op lijken: email#provider.com<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $voornaam) === 0)
{
echo '<fblack>Voornaam is niet geldig ingevoerd, heeft u een hoofdletter gebruikt?<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $achternaam) === 0)
{
echo '<fblack>Achternaam is niet geldig ingevoerd, heeft u een hoofdletter gebruikt?<br><fblack>';
$foutloos = false;
}
if ($geslacht == '')
{
echo '<fblack>U heeft uw geslacht niet aangegeven.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-zA-Z]+\ +[0-9]+$/", $adres) === 0)
{
echo '<fblack>Het adres is verkeerd ingevoerd.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-zA-Z\s]+$/", $woonplaats) === 0)
{
echo '<fblack>De woonplaats is verkeerd ingevoerd.<br><fblack>';
$foutloos = false;
}
if ($foutloos == true)
{
mysql_query($query)
or die('<fblack>U staat al in ons systeem<br><br>Klik hier om terug te gaan<fblack>');
echo "<fblack>Uw registratie is succesvol verwerkt!<br>Log <a href='login.php' MEDIA=screen>hier</a> in<fblack>";
}
else
{
echo '<fblack><br>Klik hier om terug te gaan<fblack>';
}
?>
</center>
</div>
<?php
include ("html_end.php");
?>
Now on top of the page I want to show an error message.
So how do I echo something on the top, while it catches it in the IF?
if ($foutloos == true)
{
mysql_query($query)
or die('<fblack>U staat al in ons systeem<br><br>Klik hier om terug te gaan<fblack>');
echo "<fblack>Uw registratie is succesvol verwerkt!<br>Log <a href='login.php' MEDIA=screen>hier</a> in<fblack>";
}
else
{
ECHO SOMETHING THAT HAS TO GO ABOVE THE PAGE
echo '<fblack><br>Klik hier om terug te gaan<fblack>';
}
Thanks in advance!
You want to seperate your logic from your view. So put your PHP on top, then the HTML at the bottom, for example:
//This goes at the top, only PHP here!
$host = "localhost";
$gebruikersnaam = "root";
$wachtwoord = "";
mysql_connect($host, $gebruikersnaam, $wachtwoord);
//etc
$query ="INSERT INTO vrijwilliger (voornaam, achternaam, gbdatum, geslacht, wachtwoord, woonplaats, adres, telefoonnummer, functie, activiteitID, groepID, email) VALUES('$voornaam','$achternaam','$gbdatum','$geslacht','$wachtwoord','$woonplaats','$adres','$telefoonnummer','$functie',null,null,'$email')";
$foutmelding = false; //Start without error obviously, we check later if this value has been changed at all.
if(preg_match("/^[0-9]{10}+$/", $telefoonnummer) === 0) //Something is not right
{
$foutmelding = "Je telefoon nummer klopt niet!"; //By setting this to a string it will evaluate to `true` later on, thus showing the error message.
}
//More error checking etc...
Then all the way down in your view, e.g. HTML;
<?php if($foutmelding) { ?>
Er is een fout opgetreden; <?php echo $foutmelding; ?>
<?php } else { ?>
Alles is goed gegaan, dankjewel!
<?php } ?>
Use the PHP buffers. Don't send the content of the buffer until you reach the end of the php file.
http://php.net/manual/en/book.outcontrol.php
<?php
// Open buffer #1
ob_start();
print "Line 1\n";
// Open buffer #2
ob_start();
print "Line 2\n";
// Grab the contents of buffer #2
$buf2 = ob_get_contents();
// Close buffer #2
ob_end_clean();
print "Line 3\n";
// Grab the contents of buffer #1
$buf1 = ob_get_contents();
// Close buffer #1
ob_end_clean();
// Output the buffer contents
print $buf1;
print $buf2;
?>
You have at least 2 ways of doing this:
server side - start using some template engines like smarty and separate your presentation layer from the business layer as F. Calderan suggested
client side - add some javascript code to the HTML generated by your php script. Make this execute at the end of the page and modify the DOM of the HTML.
if you don't want to rewrite your project to mvc, here is just a quick solution..: use ob_start
Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.
What I'm trying to figure out here is how to access the different array values that I need. I have the following query and it returns this for an array when the print_r() is applied. For some reason it only does the first row from the db table. It should return a whole another row.
<?php
session_start();
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = "no";
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answerPost) {
} else {
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
} else {
$errors = "yes";
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Because you just fetch the first one, where you should loop on the result set instead:
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '$userID'";
$result = mysqli_query($dbc,$query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
By the way, you should be using prepared statements to avoid SQL injection.
You need to wrap your fetch in a loop. e.g.
if (mysqli_num_rows($result) > 0)
{
while (($row = mysqli_fetch_array($result)) !== false)
{
if ($row['answer'] == $answerPost)
{
// $row matches what we're looking for
}
else
{
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
print_r($row);
}
}
im working on a part of program where i need to send null to my database if the textbox is empty here is what i have so far
<?php
//so if not connected to database it displays an error message instead of a php error recommend having on 1 in development mode - for warnings and error
ini_set( "display_errors", 0);
if(!$_POST) exit;
$con = mysql_connect("localhost","imstillr","password");
mysql_select_db("imstillr_crm", $con);
$company = protect($_POST['company']); //required
$primarycontact = protect($_POST['primarycontact']); //required
$primaryemail = protect($_POST['primaryemail']); //required
$preferphone = protect($_POST['preferphone']); //required
$secondarycontact = protect($_POST['secondarycontact']);
$secondaryemail = protect($_POST['secondaryemail']);
$optionalphone = protect($_POST['optionalphone']);
$department = protect($_POST['department']);
$website = protect($_POST['website']); //required*/
//database info
mysql_query("SELECT companyname FROM customerinfo WHERE companyname='" .$company. "'");
if (!$con)
{
//checks if database connection string is correct
echo '<div class="error_message">Attention! no database connection.</div>';
exit();
} else if(mysql_affected_rows() == 1) {
echo '<div class="error_message">Attention! This company already exists.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! You must enter your company name.</div>';
exit();
} else if(trim($primarycontact) == '') {
echo '<div class="error_message">Attention! You must enter a contact name.</div>';
exit();
} else if(trim($primaryemail) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($primaryemail)) {
echo '<div class="error_message">Attention! You have to enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($department) == '') {
echo '<div class="error_message">Attention! Please enter a department.</div>';
exit();
} else if(trim($preferphone) == '') {
echo '<div class="error_message">Attention! Please enter a preferred phone number.</div>';
exit();
} else if(!isPhone($preferphone)) {
echo '<div class="error_message">Attention! Please enter the right format for phone.</div>';
exit();
} else if(trim($website) == '') {
echo '<div class="error_message">Attention! Please enter a website name.</div>';
exit();
}
if($error == '') {
$secondarycontact = NULL;
$secondaryemail = 'random text';
$optionalphone = 'random text';
$address = "example#yahoo.com";
$clientaddress = $primaryemail;
//admin subject
$e_subject = $primarycontact .' has successfully been registered in the database';
//client subject
$c_subject = 'You have successfully been registered in the database';
/* another way of doing admin client email as array
$admin_email = array(
'e_body' => '$primarycontact has been registered in department '$department' \r\n\n',
'e_content' => 'You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n';
'e_reply' => 'You can contact $primarycontact via email, $primaryemail';
);*/
//admin email
$e_body = "$primarycontact has been registered in department '$department' \r\n\n";
//$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
//$e_content = "\"anything can be displayed here such as all the customers entered info\"\r\n\n";
$e_reply = "You can contact $primarycontact via email, $primaryemail ";
//client email
$c_body = "You has been registered in department '$department' \r\n\n";
$c_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
$c_reply = "For anymore information feel free to contact the administrator vis email, $address";
//admin msg
$msg = $e_body . $e_content . $e_reply;
//client msg
$cmsg = $c_body . $c_content . $c_reply;
//inserts information
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$preferphone."', '".$secondarycontact."', '".$secondaryemail."', '".$optionalphone."', '".$department."', '".$website."')");
if(mail($address, $e_subject, $msg, "From: $primaryemail\r\nReply-To: $primaryemail\r\nReturn-Path: $primaryemail\r\n")) {
//if mail was sent to admin then send to person who signed up
mail($primaryemail, $c_subject, $cmsg, "From: $address\r\nReply-To: $address\r\nReturn-Path: $address\r\n");
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo $secondarycontact. '<br />';
echo $secondaryemail. '<br />';
echo $optionalphone. '<br />';
//echo "<h1>User $primarycontact Successfully added onto '$department'.</h1>";
echo "<p>Thank you <strong>$primarycontact</strong>, your registration info has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
//all functions go here
//protects database from SQL injection
function protect($value) {
if(get_magic_quotes_gpc()){
return mysql_real_escape_string(stripslashes($value));
}else{
return mysql_real_escape_string($value);
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
function isPhone($number) {
return(preg_match("/^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/",$number));
}
?>
optionalphone,secondaryemail and secondarycontact are the only values that can be null
This will not work:
$foo = null;
mysql_query("INSERT INTO ... VALUES (".$foo.")");
This will:
mysql_query("INSERT INTO ... VALUES (NULL)");
So you might want to do it this way:
function quoted_string_or_null($var) {
return $var === null ? 'NULL' : "'".$var."'";
}
$foo = null;
mysql_query("INSERT INTO ... VALUES (".quoted_string_or_null($foo).")");
However, there is another problem: there is no way you will be getting real null values from your protect function or from $_POST. So you have to decide if an empty string is a legal value, or if empty strings should be converted to null. It's probably the latter, so you can make a small change and work with this:
function quoted_string_or_null($var) {
return ($var === null || $var === '') ? 'NULL' : "'".$var."'";
}
Rather than manually quoting the strings, use something to do this for you. See http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments is a function written for your issue:
<?php
function db_escape($values, $quotes = true) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$values[$key] = db_escape($value, $quotes);
}
}
else if ($values === null) {
$values = 'NULL';
}
else if (is_bool($values)) {
$values = $values ? 1 : 0;
}
else if (!is_numeric($values)) {
$values = mysql_real_escape_string($values);
if ($quotes) {
$values = '"' . $values . '"';
}
}
return $values;
}
?>
Once you have escaped each value, pass it without any extra quotes to the insert command.