Post Not Capturing Checkbox Response - php

I have a form with a group of checkboxes that when I post to the database, the responses are not being captured. Error reporting is not showing anything and the field is blank.
The odd thing I find is that I have a second checkbox group setup exactly the same that does post.
The database field is:
name: LAB_Results
type: text
My form group is:
<div class="form-row">
<div class="col-lg-4 mb-2">
<label > 3. LABORATORY RESULTS: within the past 6 months (please submit the results)</label>
</div>
<div class="col-lg-8 mb-2">
<ul class="list-group list-group-flush">
<li class="list-group-item">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="LAB_Results[]" name="LAB_Results[]" value="Chemistry Profile">
<label class="form-check-label" >Chemistry Profile</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="LAB_Results[]" id="Lab_Results[]" value="CBC">
<label class="form-check-label" >Complete Blood Count</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="LAB_Results[]" id="Lab_Results[]" value="Urinalysis">
<label class="form-check-label" >Urinalysis</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="LAB_Results[]" id="Lab_Results[]" value="Urine Culture & Susceptibility">
<label class="form-check-label" >Urine Culture & Susceptibility</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="LAB_Results[]" id="Lab_Results[]" value="Skin Bacterial Culture & Susceptibility">
<label class="form-check-label" >Skin Bacterial Culture & Susceptibility</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label" >Other Test(s)</label>
<input class="form-check-input" type="text" id="Lab_Results[]" name="LAB_Results[]" placeholder="Other Test(s)">
</div>
</li>
</ul>
</div>
</div>
</div><!-- end of card div -->
My post script is:
<?PHP
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*** THIS! ***/
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("information removed");
if (mysqli_connect_error()) { echo mysqli_connect_error(); exit; }
if (isset($_POST['submit'])){
// The (?,?,?) below are parameter markers used for variable binding
$sql = "INSERT INTO tbl_dermatology_form_rdvm (date_submitted, UMNCaseNo, ClientName, ClientPhone, Pet_Name, Species, Breed, rDVM_Clinic, rDVM, Reason_for_Referral, Relevant_History, Relevant_Clinical_Signs, Pruritus_Present, Photos_Available, Photos_Submitted, Skin_Scrapings, Skin_Scrapings_Results, Ear_Cytology, Ear_Cytology_Results, Skin_Cytology, Skin_Cytology_Results, Fungal_Culture, Fungal_Culture_Results, FNA, FNA_Results, Biopsy, Biopsy_Results, Other_Test, Other_Test_Results, Allergy_Test, Allergy_Test_Date, Food_Trial, Food_Trial_Diet, Food_Trial_Duration, Food_Trial_Response, LAB_Results, P_Tx_1, P_Tx_1_Response, P_Tx_2, P_Tx_2_Response, P_Tx_3, P_Tx_3_Response, P_Tx_4, P_Tx_4_Response, P_Tx_5, P_Tx_5_Response, C_Tx_1, C_Tx_1_Response, C_Tx_2, C_Tx_2_Response, C_Tx_3, C_Tx_3_Response, C_Tx_4, C_Tx_4_Response, C_Tx_5, C_Tx_5_Response, Additional_Care, Unrelated_Services, Comments_Special_Requests, rDVM_email, Vet_Visit_Behavior, Client_Patient_Concerns
) VALUES (NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss", $UMNCaseNo, $ClientName, $ClientPhone, $Pet_Name, $Species, $Breed, $rDVM_Clinic, $rDVM, $Reason_for_Referral, $Relevant_History, $Relevant_Clinical_Signs, $Pruritus_Present, $Photos_Available, $Photos_Submitted, $Skin_Scrapings, $Skin_Scrapings_Results, $Ear_Cytology, $Ear_Cytology_Results, $Skin_Cytology, $Skin_Cytology_Results, $Fungal_Culture, $Fungal_Culture_Results, $FNA, $FNA_Results, $Biopsy, $Biopsy_Results, $Other_Test, $Other_Test_Results, $Allergy_Test, $Allergy_Test_Date, $Food_Trial, $Food_Trial_Diet, $Food_Trial_Duration, $Food_Trial_Response, $LAB_Results, $P_Tx_1, $P_Tx_1_Response, $P_Tx_2, $P_Tx_2_Response, $P_Tx_3, $P_Tx_3_Response, $P_Tx_4, $P_Tx_4_Response, $P_Tx_5, $P_Tx_5_Response, $C_Tx_1, $C_Tx_1_Response, $C_Tx_2, $C_Tx_2_Response, $C_Tx_3, $C_Tx_3_Response, $C_Tx_4, $C_Tx_4_Response, $C_Tx_5, $C_Tx_5_Response, $Additional_Care, $Unrelated_Services, $Comments_Special_Requests, $rDVM_email, $Vet_Visit_Behavior, $Client_Patient_Concerns ); // bind variables
// Patient UMN Case Number
if (trim($_POST['UMNCaseNo']) == '') {
$UMNCaseNo = NULL;
} else {
$UMNCaseNo = trim($_POST['UMNCaseNo']);
}
// Client Name
if (trim($_POST['ClientName']) == '') {
$ClientName = NULL;
} else {
$ClientName = trim($_POST['ClientName']);
}
//Patient Name
if (trim($_POST['Pet_Name']) == '') {
$Pet_Name = NULL;
} else {
$Pet_Name = trim($_POST['Pet_Name']);
}
//Patient Species
if (trim($_POST['Species']) == '') {
$Species = NULL;
} else {
$Species = trim($_POST['Species']);
}
//Patient Breed
if (trim($_POST['Breed']) == '') {
$Breed = NULL;
} else {
$Breed = trim($_POST['Breed']);
}
//rDVM_Clinic
if (trim($_POST['rDVM_Clinic']) == '') {
$rDVM_Clinic = NULL;
} else {
$rDVM_Clinic = trim($_POST['rDVM_Clinic']);
}
//rDVM
if (trim($_POST['rDVM']) == '') {
$rDVM = NULL;
} else {
$rDVM = trim($_POST['rDVM']);
}
//Reason_for_Referral
if (trim($_POST['Reason_for_Referral']) == '') {
$Reason_for_Referral = NULL;
} else {
$Reason_for_Referral = trim($_POST['Reason_for_Referral']);
}
//Relevant_History
if(isset($_POST['Relevant_History']))
{
$Relevant_History = $_POST["Relevant_History"];
}
else {
$Relevant_History = NULL;
}
// Relevant_Clinical_Signs
if(isset($_POST['Relevant_Clinical_Signs']))
{
$Relevant_Clinical_Signs = $_POST["Relevant_Clinical_Signs"];
}
else {
$Relevant_Clinical_Signs = NULL;
}
// Pruritus_Present
if(isset($_POST['Pruritus_Present']))
{
$Pruritus_Present = $_POST["Pruritus_Present"];
}
else {
$Pruritus_Present = NULL;
}
// Photos_Available
if(isset($_POST['Photos_Available']))
{
$Photos_Available = $_POST["Photos_Available"];
}
else {
$Photos_Available = NULL;
}
// Photos_Submitted
if(isset($_POST['Photos_Submitted']))
{
$Photos_Submitted = $_POST["Photos_Submitted"];
}
else {
$Photos_Submitted = NULL;
}
// Skin_Scrapings
if(isset($_POST['Skin_Scrapings']))
{
$Skin_Scrapings = 'Y';
}
else {
$Skin_Scrapings = NULL;
}
// Skin_Scrapings_Results
if(isset($_POST['Skin_Scrapings_Results']))
{
$Skin_Scrapings_Results = $_POST["Skin_Scrapings_Results"];
}
else {
$Skin_Scrapings_Results = NULL;
}
// Ear_Cytology
if(isset($_POST['Ear_Cytology']))
{
$Ear_Cytology = 'Y';
}
else {
$Ear_Cytology = NULL;
}
// Ear_Cytology_Results
if(isset($_POST['Ear_Cytology_Results']))
{
$Ear_Cytology_Results = $_POST["Ear_Cytology_Results"];
}
else {
$Ear_Cytology_Results = NULL;
}
// Skin_Cytology
if(isset($_POST['Skin_Cytology']))
{
$Skin_Cytology = 'Y';
}
else {
$Skin_Cytology = NULL;
}
// Skin_Cytology_Results
if(isset($_POST['Skin_Cytology_Results']))
{
$Skin_Cytology_Results = $_POST["Skin_Cytology_Results"];
}
else {
$Skin_Cytology_Results = NULL;
}
// Fungal_Culture
if(isset($_POST['Fungal_Culture']))
{
$Fungal_Culture = 'Y';
}
else {
$Fungal_Culture = NULL;
}
// Fungal_Culture_Results
if(isset($_POST['Fungal_Culture_Results']))
{
$Fungal_Culture_Results = $_POST["Fungal_Culture_Results"];
}
else {
$Fungal_Culture_Results = NULL;
}
// FNA
if(isset($_POST['FNA']))
{
$FNA = 'Y';
}
else {
$FNA = NULL;
}
// FNA_Results
if(isset($_POST['FNA_Results']))
{
$FNA_Results = $_POST["FNA_Results"];
}
else {
$FNA_Results = NULL;
}
// Biopsy
if(isset($_POST['Biopsy']))
{
$Biopsy = 'Y';
}
else {
$Biopsy = NULL;
}
// Biopsy_Results
if(isset($_POST['Biopsy_Results']))
{
$Biopsy_Results = $_POST["Biopsy_Results"];
}
else {
$Biopsy_Results = NULL;
}
if(isset($_POST['Other_Test']))
{
$Other_Test = 'Y';
}
else {
$Other_Test = NULL;
}
// Other_Test_Results
if(isset($_POST['Other_Test_Results']))
{
$Other_Test_Results = $_POST["Other_Test_Results"];
}
else {
$Other_Test_Results = NULL;
}
// Allergy_Test
if(isset($_POST['Allergy_Test']))
{
$Allergy_Test = $_POST["Allergy_Test"];
}
else {
$Allergy_Test = NULL;
}
// Allergy_Test_Date
if(isset($_POST['Allergy_Test_Date']))
{
$Allergy_Test_Date = $_POST["Allergy_Test_Date"];
}
else {
$Allergy_Test_Date = NULL;
}
// Food_Trial
if(isset($_POST['Food_Trial']))
{
$Food_Trial = $_POST["Food_Trial"];
}
else {
$Food_Trial = NULL;
}
// Food_Trial_Diet
if(isset($_POST['Food_Trial_Diet']))
{
$Food_Trial_Diet = $_POST["Food_Trial_Diet"];
}
else {
$Food_Trial_Diet = NULL;
}
// Food_Trial_Duration
if(isset($_POST['Food_Trial_Duration']))
{
$Food_Trial_Duration = $_POST["Food_Trial_Duration"];
}
else {
$Food_Trial_Duration = NULL;
}
// Food_Trial_Response
if(isset($_POST['Food_Trial_Response']))
{
$Food_Trial_Response = $_POST["Food_Trial_Response"];
}
else {
$Food_Trial_Response = NULL;
}
// lab results
if(!empty($_POST['LAB_Results'])){
$Lab_Results = implode(', ', $_POST['LAB_Results']);
} else {
$Lab_Results = NULL;
}
// vet visit behavior
if(!empty($_POST['Vet_Visit_Behavior'])){
$Vet_Visit_Behavior = implode(', ', $_POST['Vet_Visit_Behavior']);
} else {
$Vet_Visit_Behavior = NULL;
}
// P_Tx_1
if(isset($_POST['P_Tx_1']))
{
$P_Tx_1 = $_POST["P_Tx_1"];
}
else {
$P_Tx_1 = NULL;
}
// P_Tx_1_Response
if(isset($_POST['P_Tx_1_Response']))
{
$P_Tx_1_Response = $_POST["P_Tx_1_Response"];
}
else {
$P_Tx_1_Response = NULL;
}
// P_Tx_2
if(isset($_POST['P_Tx_2']))
{
$P_Tx_2 = $_POST["P_Tx_2"];
}
else {
$P_Tx_2 = NULL;
}
// P_Tx_2_Response
if(isset($_POST['P_Tx_2_Response']))
{
$P_Tx_2_Response = $_POST["P_Tx_2_Response"];
}
else {
$P_Tx_2_Response = NULL;
}
// P_Tx_3
if(isset($_POST['P_Tx_3']))
{
$P_Tx_3 = $_POST["P_Tx_3"];
}
else {
$P_Tx_3 = NULL;
}
// P_Tx_3_Response
if(isset($_POST['P_Tx_3_Response']))
{
$P_Tx_3_Response = $_POST["P_Tx_3_Response"];
}
else {
$P_Tx_3_Response = NULL;
}
// P_Tx_4
if(isset($_POST['P_Tx_4']))
{
$P_Tx_4 = $_POST["P_Tx_4"];
}
else {
$P_Tx_4 = NULL;
}
// P_Tx_4_Response
if(isset($_POST['P_Tx_4_Response']))
{
$P_Tx_4_Response = $_POST["P_Tx_4_Response"];
}
else {
$P_Tx_4_Response = NULL;
}
// P_Tx_5
if(isset($_POST['P_Tx_5']))
{
$P_Tx_5 = $_POST["P_Tx_5"];
}
else {
$P_Tx_5 = NULL;
}
// P_Tx_5_Response
if(isset($_POST['P_Tx_5_Response']))
{
$P_Tx_5_Response = $_POST["P_Tx_5_Response"];
}
else {
$P_Tx_5_Response = NULL;
}
// C_Tx_1
if(isset($_POST['C_Tx_1']))
{
$C_Tx_1 = $_POST["C_Tx_1"];
}
else {
$C_Tx_1 = NULL;
}
// C_Tx_1_Response
if(isset($_POST['C_Tx_1_Response']))
{
$C_Tx_1_Response = $_POST["C_Tx_1_Response"];
}
else {
$C_Tx_1_Response = NULL;
}
// C_Tx_2
if(isset($_POST['C_Tx_2']))
{
$C_Tx_2 = $_POST["C_Tx_2"];
}
else {
$C_Tx_2 = NULL;
}
// C_Tx_2_Response
if(isset($_POST['C_Tx_2_Response']))
{
$C_Tx_2_Response = $_POST["C_Tx_2_Response"];
}
else {
$C_Tx_2_Response = NULL;
}
// C_Tx_3
if(isset($_POST['C_Tx_3']))
{
$C_Tx_3 = $_POST["C_Tx_3"];
}
else {
$C_Tx_3 = NULL;
}
// C_Tx_3_Response
if(isset($_POST['C_Tx_3_Response']))
{
$C_Tx_3_Response = $_POST["C_Tx_3_Response"];
}
else {
$C_Tx_3_Response = NULL;
}
// C_Tx_4
if(isset($_POST['C_Tx_4']))
{
$C_Tx_4 = $_POST["C_Tx_4"];
}
else {
$C_Tx_4 = NULL;
}
// C_Tx_4_Response
if(isset($_POST['C_Tx_4_Response']))
{
$C_Tx_4_Response = $_POST["C_Tx_4_Response"];
}
else {
$C_Tx_4_Response = NULL;
}
// C_Tx_5
if(isset($_POST['C_Tx_5']))
{
$C_Tx_5 = $_POST["C_Tx_5"];
}
else {
$C_Tx_5 = NULL;
}
// C_Tx_5_Response
if(isset($_POST['C_Tx_5_Response']))
{
$C_Tx_5_Response = $_POST["C_Tx_5_Response"];
}
else {
$C_Tx_5_Response = NULL;
}
// Additional_Care
if(isset($_POST['Additional_Care']))
{
$Additional_Care = $_POST["Additional_Care"];
}
else {
$Additional_Care = NULL;
}
// Unrelated_Services
if(isset($_POST['Unrelated_Services']))
{
$Unrelated_Services = $_POST["Unrelated_Services"];
}
else {
$Unrelated_Services = NULL;
}
// Comments_Special_Requests
if(isset($_POST['Comments_Special_Requests']))
{
$Comments_Special_Requests = trim($_POST["Comments_Special_Requests"]);
}
else {
$Comments_Special_Requests = NULL;
}
// rDVM email address
if(isset($_POST['rDVM_email'])) {
$rDVM_email = filter_var($_POST['rDVM_email'], FILTER_SANITIZE_EMAIL);
} else {
$rDVM_email = NULL;
}
// client or patient concerns
if(isset($_POST['Client_Patient_Concerns'])) {
$Client_Patient_Concerns = trim($_POST['Client_Patient_Concerns']);
} else {
$Client_Patient_Concerns = NULL;
}
if ($stmt->execute()) {
$last_id = $stmt->insert_id;
$headers = "From: " . strip_tags($email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body><h3>An rDVM Dermatology Questionnaire Has Been Submitted.</h3><br />';
$message .= "<br />";
$message .= "<br />";
$message .= "Thank you " .$rDVM ." for filling out the Dermatology form for " .$Pet_Name . " with, ". $ClientName . ". Your information has been received. If indicated, please use the following link <a href=".$url." target='_blank'>" .$url . "</a> to submit any photographs of your patients lesions or documents / test results. ";
$message .= "<br />";
$message .= "<br />";
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'> <td width='178'></td> <td width='380'></td></tr>";
$message .= "<tr> <td><strong>Case/PA Number:</strong></td> <td>" . $UMNCaseNo . "</td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "<tr> <td><strong>Client Name:</strong> </td><td>" . $ClientName . "</td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "<tr><td><strong>Pet Name:</strong></td> <td>" . $Pet_Name . "</td></tr>";
$message .= "<tr><td><strong>Species:</strong></td> <td>" . $Species . "</td></tr>";
$message .= "<tr><td><strong>Breed:</strong></td> <td>" . $Breed . "</td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "<tr><td><strong>Clinic Name:</strong></td> <td>" . $rDVM_Clinic . "</td></tr>";
$message .= "<tr><td><strong>rDVM Name:</strong></td> <td>" . $rDVM . "</td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "<tr style='background: #eee'><td colspan='2'><strong>Reason for Referral & Expectations:</strong></td></tr>";
$message .= "<tr><td colspan='2'>" . $Reason_for_Referral . "</td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "<tr><td colspan='2'>Link to full history (available to UMN Staff Only): <a href='http://xxx/dermatology/form_view_rdvm.php?id=". $last_id ."' target='_blank'> http://xxx/dermatology/form_view_rdvm.php?id=". $last_id . "</a></td></tr>";
$message .= "<tr><td colspan='2'> </td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$message .= "<br />";
if(mail($to,$subject,$message,$headers)){
//redirect to the 'thank you' page
echo "<body><br /><br />
Thank you " .$rDVM ." for filling out the Dermatology form for " .$Pet_Name . " with, ". $ClientName . ". Your information has been received. Use the following link <a href=".$url." target='_blank'>" .$url . "</a> to submit photographs of your patients lesions or documents / test results
</body>";
} else {
echo 'Error!';
}
}
}
$stmt->close(); // close the prepared statement
$mysqli->close(); // close the database connection
?>

I would remove the square brackets on the field name. Probably you are receiving your data in the $_POST['LAB_Results[]'] variable.
As said #noid you must avoid duplicated ids.
Copied from the comments.
Please remove the last field, the text input named Lab_Results, the Other tests one. Probably you will have to deal with that field separately from the checkboxes.

Related

Dynamic update statement - prepared statement

I am generating my MYSQL update statement dynamically in PHP. As I want my application to be secure to SQL injections I want to use the prepared statement function. But as I'm pretty experienced I'm struggling to do so. Below my code so far:
function sqlUpdate($tablename)
{
$connect = sqlConnect();
$updateString = "UPDATE " . $tablename . " SET ";
$columnname = getColumnname($tablename, false, true);
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
if ($k+1 < count($columnname, COUNT_RECURSIVE))
{
$updateString .= $columnname[$k] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[$k]]) . "', ";
}
else
{
$updateString .= $columnname[$k] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[$k]]) . "' WHERE " . $columnname[0] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[0]]) . "';";
}
}
if(mysqli_query($connect, $updateString))
{
echo "Daten wurden erfolgreich aktualisiert! </br>";
}
else
{
echo "Es ist ein Fehler aufgetreten... </br>";
}
mysqli_close($connect);
}
My code is working fine at the moment but I'm not managing to get it to work with prepared statements. I hope my question is not too stupid. Can somebody share some thoughts how to realize it with my code or do I have to completly overthink my approach?
Sorry again for my noob question...
Thanks!
Thanks to everybody who answered I managed to get it to work. I used the call_user_func_array function and can now generate the prepared statements for UPDATE and INSERT in one function:
function preparedStatement($tableName, $action)
{
$connect = sqlConnect();
$stmt = $connect->stmt_init();
$columnname = getColumnname($tableName, false, true);
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
$fielddata[] = $columnname[$k];
$fieldvalue[] = $_POST[$columnname[$k]];
}
if ($action == "insert")
{
$fieldvalue[0] = " ";
}
$fieldvalue_join = implode(',', array_map('addquote', $fieldvalue));
$fieldvalue = explode(",",$fieldvalue_join);
$valueCount = count($fieldvalue);
$question_mark = array();
for($i=0; $i<$valueCount; $i++)
{
$question_mark[] = '?';
}
$join_question_mark = implode(",", $question_mark);
$types = '';
foreach($fieldvalue as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}
elseif (is_float($param))
{
$types .= 'd'; //double
}
elseif (is_string($param))
{
$types .= 's'; //string
}
else
{
$types .= 'b'; //blob and unknown
}
}
if ($action == "insert")
{
$insertString = "INSERT INTO ".$tableName."(".implode(",",$fielddata).") VALUES (".$join_question_mark.");";
$stmt->prepare($insertString);
$bind_names[] = $types;
}
elseif ($action == "update")
{
$updateString = "UPDATE " . $tableName . " SET ";
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
if ($k+1 < count($columnname, COUNT_RECURSIVE))
{
$updateString .= $columnname[$k] . " = ?, ";
}
else
{
$updateString .= $columnname[$k] . " = ? WHERE " . $columnname[0] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[0]]) . "';";
}
}
$stmt->prepare($updateString);
$bind_names[] = $types;
}
for ($i=0; $i<count($fieldvalue); $i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $fieldvalue[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
if($stmt->execute())
{
$insert_id=$stmt->insert_id;
$stmt->close();
return $insert_id;
}
else
{
echo "Fehler beim Ausführen der Aktion...";
}
}
function addquote($str)
{
if($str[0]=="'" || $str[0]=='"' && $str[strlen($str)-1]=="'" || $str[strlen($str)-1]=="'" )
{
$str=substr($str,1);
$str=substr($str,0,-1);
}
return sprintf("%s", $str);
}

PHP/Mysql input value on column become null when another column value change

I just extend a column on my db table. So I try to put data on that table. I have 10 more column on that table. There is a column name _source_ and if its value become 1 then my new column input data correctly. but if its value became 2 then my new column show null. I check and re-check my function from last two days. I can't understand what I am missing!
Here is my full function PHP code:
function regular_upload($inputname, $ftp_server){
global $site_url;
$ok=1;
$upload_name = $inputname;
// AICI VERIFICAM DACA A FOST ADAUGATA O FILA
if (!isset($_FILES[$upload_name])) {
//header('Location: index.php');
echo 'No upload found in \$_FILES for ' . $upload_name;
$ok=0;
//exit();
} else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) {
// echo $uploadErrors[$_FILES[$upload_name]['error']];
echo "<p class='error'>No files</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name'])) {
echo "<p class='error'>Upload failed is_uploaded_file test.</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['name'])) {
$ok=0;
echo "<p class='error'>File has no name.</p>";
//exit();
}
// DACA ADULT NU E NUMERIC DIEEEEE
if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
$adult = $_POST['adult'];
} else {
die("You didn't specify if your file(s) are Adult or Non-Adult");
}
if(is_numeric($_POST['thumb_size_contaner'])) {
$thumbnail_size = $_POST['thumb_size_contaner'];
} else {
die("Injection detected");
}
if($ok == 1) {
// verificare tipul de imagini - un fel de whitelist
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
// blacklist ce nu tre sa fie
$filename = strtolower($_FILES[$upload_name]['name']);
$blacklist = array('php', 'php3', 'php4', 'phtml','exe'); #example of black list
foreach ($blacklist as $item) {
if(preg_match("/$item\$/i", $filename)) {
echo "<p class='error'>We do not allow uploading PHP files</p>";
$ok=0;
//exit();
}
}
}
if($ok == 1) {
// de aici setam dimensiunea maxima a imaginii
list($width, $height, $type, $attr) = getimagesize($_FILES[$upload_name]['tmp_name']);
if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
{
echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
$q = "SELECT img, thumb FROM sources WHERE id = '1'";
$result = mysql_query($q);
if(mysql_num_rows($result) > 0) {
$rowSources = mysql_fetch_array($result);
} else {
die("Something went wrong : ". mysql_error());
}
$data_year = date('Y');
$data_month = date('m');
$data_day = date('d');
if($ftp_server == 0) {
$dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
if(!file_exists($dir) OR !is_dir($dir)){
mkdir($dir, 0777, true);
}
if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
mkdir($dirthumb, 0777, true);
}
} else {
$q = "SELECT * FROM ftp_logins
INNER JOIN sources ON ftp_logins.source_id = sources.id
WHERE ftp_logins.id = $ftp_server
";
$result = mysql_query($q);
if(!$result) {
echo mysql_error();
}
$rowFTP = mysql_fetch_assoc($result);
$dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$FTP = new FTP();
$FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
global $ftp_conn_id;
if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
}
if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
}
}
//$uniquenumber = uniqid('', true);
$uniquenumber = uniqid();
$view_id = uniqid();
$target = $dir;
$extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
//$filename = $_FILES['uploaded']['name'];
$nameimage = $uniquenumber . "." . $extension;
$target = $target . "/" . $uniquenumber . "." . $extension;
$uploaded_size = $_FILES[$upload_name]['size'];
//echo $uploaded_size;
//This is our size condition
if ($uploaded_size > MAX_UPLOAD_SIZE*1024) { // IN KB
echo "<p class='error'>Your file is too large.</p>";
$ok=0;
}
}
//This is our limit file type condition
if ($ok==0) {
echo "<p class='error'>Sorry your file was not uploaded </p>";
} else {
//If everything is ok we try to upload it
if($ftp_server == 0) {
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $target)) {
echo "<p class='success'> ". basename( $_FILES[$upload_name]['name']). " has been succesfuly uploaded </p>";
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$target_thumb = $dirthumb;
$resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
$image = new SimpleImage();
$image->load($target);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($resizeuploadpatch);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$site_url}/{$dir}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$site_url}/{$dir}/{$nameimage}</div>";
} else {
echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
}
} else { // if FTP SERVER
$ftp_temp_img = "cache/ftp/".$nameimage."";
$ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $ftp_temp_img)) {
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$image = new SimpleImage();
$image->load($ftp_temp_img);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($ftp_temp_thumb);
}
if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_img in $target\n";
} else {
//echo "There was a problem while uploading $ftp_temp_img in $target\n";
}
if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
} else {
//echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
}
$FTP->disconnect($ftp_conn_id);
unlink($ftp_temp_img);
unlink($ftp_temp_thumb);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";
} // ftp end
} // ELSE IF EVERYTING IS OK, IF ERROR = 0
} // END FUNCTION
I am really frustrated with this and I can't find what is causing the error.
Here is the database screenshot:

PHP Anti-Spam field

I have a problem with my email form. Everything works fine, except the Anti-Spam field.
The anti-Spam field shows me a wrong answer in all situations. Both if it is true and false, but when i leave the field blank, then the email is send correctly. So this is problem one.
Problem two is: I want when the Anti-Spam answer is correct then a new question not to be generated. I want to remember the question and the answer, when the answer is correct
So look at my code and please help me? what i am doing wrong?
PHP code:
<?php
require './PHPMailer/PHPMailerAutoload.php';
// varijable
$err_name = $err_email = $err_message = $err_forma = $uspesno = $captcha = "";
$name = $email = $message = $user_result = $arg_1 = $arg_2 ="";
// Konfiguracija PHPMailer-a
$mailer = new PHPMailer;
try {
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? $_POST['name'] : FALSE;
$email = isset($_POST['email']) ? $_POST['email'] : FALSE;
$message = isset($_POST['message']) ? $_POST['message'] : FALSE;
$user_result = isset($_POST['result']) ? $_POST['result'] : FALSE;
$arg_1 = isset($_POST['arg_one']) ? $_POST['arg_one'] : FALSE;
$arg_2 = isset($_POST['arg_two']) ? $_POST['arg_two'] : FALSE;
$mailer->From = $email; // Email posaljioca
$mailer->FromName = "Nova Porudzbina"; // Ime Posaljioca
$mailer->AddAddress("blabla#gmail.com"); //adresa na koju se salje
$mailer->isHTML(TRUE); // set email format to HTML
$mailer->WordWrap = 50; // set word wrap to 50 characters
$mailer->CharSet = "utf-8"; //"ukljucuje" cirlicna slova, kao i latinicna sa kvacicama
$mailer->Subject = 'zahtev za podršku: ' . $naziv_servera;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$name_exp = "/^[A-Za-z\p{L} .'-]{2,40}+$/u"; // Dozvoljava naša slova i ograničava da najmanje može 2 a najviše 40 karaktera
if (!preg_match($name_exp, $name)) {
$err_name .= 'Vaše ime nije validno.';
}
$email = test_input($_POST["email"]);
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email)) {
$err_email .= 'Vaša e-mail adresa nije validna.';
}
$message = test_input($_POST["message"]);
$message_exp = "/^[A-Za-z\p{L} .'-]{2,400}+$/u";
if (!preg_match($message_exp, $message)) {
$err_message .= 'Vaša poruka nije validna.';
}
$user_result = test_input($_POST["result"]);
if($total <> $user_result) {
$captcha .= 'Anti-spam odgovor koji ste uneli nije tačan.';
}
}
// Body
$body = "<h2 style='background: red; color: #fff;'>Nova Porudzbina</h2>";
$body .= "<b>Ime i Prezime:</b>" . $name . "<br>";
$body .= "<b>Email:</b>" . $email . "<br>";
$body .= "<b>Poruka:</b>" . $message . "<br>";
$mailer->Body = $body;
// Posalji
if (strlen($err_name == "" && $err_email == "" && $err_message == "" && $total == $user_result)) {
$mailer->send(); // ako nema nikakve greške - pošalji e-mail
$uspesno .= 'Vasa poruka je poslata';
}
}
}
catch (phpmailerException $ex) {
echo $ex->errorMessage();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
}
function createCaptcha($arg_1 = '', $arg_2 = '', $total = 0)
{
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
HTML code:
<?php
include "send_email.php";
?>
<?php createCaptcha(); ?>
<span><?php echo $uspesno;?></span>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<div class="name">Name:</div>
<input name="name" type="text" value="<?php echo $name;?>" size="30"/>
<span><?php echo $err_name;?></span>
<div class="email">Email:</div>
<input name="email" type="text" value="<?php echo $email;?>" size="30"/>
<span><?php echo $err_email;?></span>
<div class="message">Message:</div>
<textarea name="message" rows="7" cols="30"><?php echo $message;?></textarea><br>
<span><?php echo $err_message;?></span><br><br>
<label>Anti-Spam:</label>
<input type="text" name="arg_one" value="<?php echo generateFieldNumber();?>" size="2">
+ <input type="text" name="arg_two" value="<?php echo generateFieldNumber();?>" size="2">
= <input type="text" name="result" value="<?php echo $user_result;?>" size="2">
<span><?php echo $captcha;?></span><br>
<input type="submit" name="submit" value="Submit" id="submit">
</form>
In order to change the values of $user_result inside createCaptcha you need to declare it as global in your function.
function createCaptcha() {
global $user_result, $arg_1, $arg_2, $total;
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
#Alon
Thanks, I found the solution for problem one:
But second problem still exist.
This is solution for problem one:
<?php
require './PHPMailer/PHPMailerAutoload.php';
// varijable
$err_name = $err_email = $err_message = $err_forma = $uspesno = $captcha = "";
$name = $email = $message = $user_result = $arg_1 = $arg_2 = "";
// Konfiguracija PHPMailer-a
$mailer = new PHPMailer;
try {
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? $_POST['name'] : FALSE;
$email = isset($_POST['email']) ? $_POST['email'] : FALSE;
$message = isset($_POST['message']) ? $_POST['message'] : FALSE;
$user_result = isset($_POST['result']) ? $_POST['result'] : FALSE;
$arg_1 = isset($_POST['arg_one']) ? $_POST['arg_one'] : FALSE;
$arg_2 = isset($_POST['arg_two']) ? $_POST['arg_two'] : FALSE;
$total = $arg_1 + $arg_2;
$mailer->From = $email; // Email posaljioca
$mailer->FromName = "Nova Porudzbina"; // Ime Posaljioca
$mailer->AddAddress("blabla#gmail.com"); //adresa na koju se salje
$mailer->isHTML(TRUE); // set email format to HTML
$mailer->WordWrap = 50; // set word wrap to 50 characters
$mailer->CharSet = "utf-8"; //"ukljucuje" cirlicna slova, kao i latinicna sa kvacicama
$mailer->Subject = 'zahtev za podršku: ' . $naziv_servera;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$name_exp = "/^[A-Za-z\p{L} .'-]{2,40}+$/u"; // Dozvoljava naša slova i ograničava da najmanje može 2 a najviše 40 karaktera
if (!preg_match($name_exp, $name)) {
$err_name .= 'Vaše ime nije validno.';
}
$email = test_input($_POST["email"]);
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email)) {
$err_email .= 'Vaša e-mail adresa nije validna.';
}
$message = test_input($_POST["message"]);
$message_exp = "/^[A-Za-z\p{L} .'-]{2,400}+$/u";
if (!preg_match($message_exp, $message)) {
$err_message .= 'Vaša poruka nije validna.';
}
$user_result = test_input($_POST["result"]);
if($total <> $user_result) {
$captcha .= 'Anti-spam odgovor koji ste uneli nije tačan.';
}
}
// Body
$body = "<h2 style='background: red; color: #fff;'>Nova Porudzbina</h2>";
$body .= "<b>Ime i Prezime:</b>" . $name . "<br>";
$body .= "<b>Email:</b>" . $email . "<br>";
$body .= "<b>Poruka:</b>" . $message . "<br>";
$mailer->Body = $body;
// Posalji
if (strlen($err_name == "" && $err_email == "" && $err_message == "" && $captcha == "")) {
$mailer->send(); // ako nema nikakve greške - pošalji e-mail
$uspesno .= 'Vasa poruka je poslata';
}
}
}
catch (phpmailerException $ex) {
echo $ex->errorMessage();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
}
function createCaptcha() {
global $user_result, $arg_1, $arg_2, $total;
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
Problem second maybe...
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
if($captcha == "")
/* than remember or stop generate new number ? */
}

MySQL Error: Duplicate 'Candidate Name'

I have created a MySQL database along with a front-end to manipulate it using PHP. However, while I can add content to the database manually, I cannot utilize my front-end. When I try to submit the data in my front-end's form fields, I receive the prompt "Duplicate Candidate Name."
The following PHP file is my general script for displaying the front-end:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info
= "SELECT candi_first
FROM question_info
WHERE candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>
Here begins my "main file" for editing:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info="select candi_first
from question_info
where candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>

Combine two columns in one table to one output

I a have a table like this:
and I want to combine colums 'uitvoeringid' and 'uitvoeringoms' and output as one with space between them.
This is my class:
public function getBanden($id = NULL, $merk = NULL, $seizoen = NULL)
{
$sql = "SELECT * FROM Uitvoering";
if(!empty($id))
{
$sql .= " WHERE uitvoeringid=:id";
if(!empty($merk)) { $sql .= " AND merkcode=:merk"; }
if(!empty($seizoen)) { $sql .= " AND uitvoeringseizoen=:seizoen"; }
}
else if(!empty($merk))
{
$sql .= " WHERE merkcode=:merk";
if(!empty($seizoen)) { $sql .= " AND uitvoeringseizoen=:seizoen"; }
$sql .= " ORDER BY uitvoeringvoertuigtype ASC, uitvoeringoms ASC";
}
try
{
$stmt = $this->db->prepare($sql);
if(!empty($id)) { $stmt->bindParam(":id", $id, PDO::PARAM_INT); }
if(!empty($merk)) { $stmt->bindParam(":merk", $merk, PDO::PARAM_STR); }
if(!empty($seizoen)) { $stmt->bindParam(":seizoen", $seizoen, PDO::PARAM_STR); }
$stmt->execute();
$this->bandenlijst = $stmt->fetchAll(PDO::FETCH_OBJ);
$stmt->closeCursor();
return $this->bandenlijst;
}
catch (Exception $e)
{
die ( $e->getMessage() );
}
}
This is a part of my file where I output the data:
if(isset($_POST['band_submit']) && $_POST['band_submit'] == "Zoek" || isset($_GET['merk']) && isset($_GET['type']) && isset($_GET['profiel']))
{
$merk = NULL;
$seizoentype = NULL;
if(isset($_POST['band_submit']) && $_POST['band_submit'] == "Zoek")
{
if($_POST['band_seizoen'] != "0") { $seizoentype = $_POST['band_seizoen']; }
$merk = $_POST['band_merk'];
}
else if(isset($_GET['merk']) && isset($_GET['type']))
{
if($_GET['type'] != "0") { $seizoentype = $_GET['type']; }
$merk = $_GET['merk'];
}
else { $seizoentype = NULL; $merk = NULL; }
$strSeizoen = NULL;
if ($seizoentype == "ZO") { $strSeizoen = "Onze zomerbanden"; }
elseif ($seizoentype == "WI") { $strSeizoen = "Onze winterbanden"; }
elseif ($seizoentype == "AS") { $strSeizoen = "Onze All-seasonbanden"; }
elseif ($seizoentype == "OV") { $strSeizoen = "Onze Overige banden"; }
else { $strSeizoen = "Alle A-merken en topklasse huismerken"; }
echo "\t\t\t\t\t<h2>" . $strSeizoen . "</h2>
\t\t\t\t\t<br />\n";
$merken = $merkclass->getMerken($merk);
$banden = $bandclass->getBanden(NULL, $merk, $seizoentype);
$nCount = 0;
$selband = NULL;
?>
<img src="http://www.website.net/logos/<?php echo str_replace(".png", "_150.png", $merken[0]->merk_logo); ?>" width="150" class="logo" alt="<?php echo $merken[0]->merk_naam; ?>"/>
<div id="merken">
<ul>
<?php
foreach($banden as $band)
{
?>
<li><a href="http://example-website.com/<?php
echo $band->merkcode;?>/<?php if(isset($seizoentype) && $seizoentype == "ZO") {echo "zomerbanden";}
else if ($seizoentype == "WI") {echo "winterbanden";}
else if ($seizoentype == "AS") {echo "all-season-banden";}
else if ($seizoentype == "OV") {echo "overig";}
else{ echo "alle-types";}?>/<?php echo $band->uitvoeringid;?>">
<?php echo str_replace(array(' ', ',', '/', '!'), '-',strtolower($band->uitvoeringoms));?>
</a>
</li>
<?php
if(isset($_GET['profiel']) && $band->uitvoeringid == $_GET['profiel']) { $selband = $band; }
$nCount++;
}
if(empty($selband) && count($banden) > 0)
{
$selband = $banden[0];
}
else if(count($banden) > 0)
{
}
else
{
echo "\t\t\t\t\t\t\t<li>Nothing Found</li>\n";
}
?>
</ul>
<div class="clearboth"></div>
</div>
How can I manage to keep the working of this the same but combine 'uitvoeringid' and 'uitvoeringoms' to one output.
So in this part:
<a href="http://example-website.com/<?php
echo $band->merkcode;?>/<?php if(isset($seizoentype) && $seizoentype == "ZO") {echo "zomerbanden";}
else if ($seizoentype == "WI") {echo "winterbanden";}
else if ($seizoentype == "AS") {echo "all-season-banden";}
else if ($seizoentype == "OV") {echo "overig";}
else{ echo "alle-types";}?>/<?php echo $band->uitvoeringid;?>">
<?php echo str_replace(array(' ', ',', '/', '!'), '-',strtolower($band->uitvoeringoms));?>
</a>
I want this line <?php echo $band->uitvoeringid;?> to be 'uitvoeringoms' and 'uitvoeringid' combined to something like "test-2341"
I tried something like:
$sql = "SELECT concat(uitvoeringid, uitvoeringoms) AS single FROM Uitvoering";
But I still want to SELECT everything and not only (uitvoeringid, uitvoeringoms)
I got a bit lost trying to get this working in a good way. Can somebody help me please? :)
It was very hard to explain this in a good way for me so I hope you guys understand it.
Thanks
Isn't this what you are looking for? A space in the middle?
$sql = "SELECT *,concat(uitvoeringid, ' ', uitvoeringoms) AS single FROM Uitvoering";
Or simply:
echo $uitvoeringsid.' '.$uitvoeringoms;
You can have both everything and combined data:
$sql = "SELECT *, concat(uitvoeringid, " ", uitvoeringoms) AS single FROM Uitvoering";
You can use same statement to get all columns but you need to specify the columns names in statement, like below:
$sql = "SELECT concat(uitvoeringid, ' ' ,uitvoeringoms) AS single, Col_1, Col_2... FROM Uitvoering";

Categories