How To Echo Values Stored As Array in MYSQL? - php

Hello Currently I have a MYSQL DB in which I post form data into. I then USE PHP to echo the data out and see the form info. Recently I added a check box and the values of the check box get stored as an ARRAY. When I go to echo my DB the output I get is
Name,Date,Array,Array
Instead of getting the word ARRAY I would like to get the value of the submission. I know you are supposed to use the implode command but I could not figure out a way to incorporate it into my code. The retrieval code looks like this. With field_10,field_11,field_12 returning just the word ARRAY.
<html>
<head>
</head>
<body>
<style>
body {background-color:#DAD8EE}
</style>
<img class="formInfo" src="ree.jpg" alt="" style="width:1000px;">
<?
$con = mysql_connect("localhost","dk1","root1");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("usersignup", $con);
$query = "SELECT * FROM `users`";
$comments = mysql_query($query);
echo "<h1> User Sign Ups </h1>";
while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
$company=$row['field_1'];
$name=$row['field_2'];
$contact_numb=$row['field_3'];
$email_adress=$row['field_4'];
$conf_yr=$row['field_5'];
$dt_arrival=$row['field_6'];
$arrival_tm=$row['field_7'];
$dt_depart=$row['field_8'];
$departure_tm=$row['field_9'];
$dnr_one=$row['field_10'];
$dnr_two=$row['field_11'];
$cmd_shw=$row['field_12'];
$company = htmlspecialchars($row['field_1'],ENT_QUOTES);
$name = htmlspecialchars($row['field_2'],ENT_QUOTES);
$contact_numb = htmlspecialchars($row['field_3'],ENT_QUOTES);
$email_adress = htmlspecialchars($row['field_4'],ENT_QUOTES);
$conf_yr = htmlspecialchars($row['field_5'],ENT_QUOTES);
$dt_arrival = htmlspecialchars($row['field_6'],ENT_QUOTES);
$arrival_tm = htmlspecialchars($row['field_7'],ENT_QUOTES);
$dt_depart= htmlspecialchars($row['field_8'],ENT_QUOTES);
$departure_tm = htmlspecialchars($row['field_9'],ENT_QUOTES);
$dnr_one= htmlspecialchars($row['field_10'],ENT_QUOTES);
$dnr_two= htmlspecialchars($row['field_11'],ENT_QUOTES);
$cmd_shw= htmlspecialchars($row['field_12'],ENT_QUOTES);
echo " <div style='margin:30px 0px;'>
<ul>
<li>Name: $name<br /></li>
<li>Company: $company<br /></li>
<li>Contact Number: $contact_numb<br /></li>
<li> Email Adress: $email_adress<br /></li>
<li> Conference Year: $conf_yr<br /></li>
<li> Date of Arrival: $dt_arrival<br /></li>
<li> Arrival Time: $arrival_tm<br /></li>
<li> Date of Departure: $dt_depart<br /></li>
<li> Departure Time: $departure_tm</br></li>
<li> Dinner on the 14th?: $dnr_one</br></li>
<li> Dinner on the 15th?: $dnr_two</br></li>
<li> Comedy Show?: $cmd_shw</br></li>
</div>
";
}
mysql_close($con);
?>
The form processing code is this
<?php
$where_form_is="http://".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9,field_10,field_11,field_12) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . $_POST['field_3'] . "','" . $_POST['field_4'] . "','" . $_POST['field_5'] . "','" . $_POST['field_6'] . "','" . $_POST['field_7'] . "','" . $_POST['field_8'] . "','" . $_POST['field_9'] . "','" . $_POST['field_10'] . "','" . $_POST['field_11'] . "','" . $_POST['field_12'] . "')";
mysql_query($query);
mysql_close($link);
include("confirms.html");
?>
The Form itself
<div id="mainForm">
<div id="formHeader">
<img class="formInfo" src="ree.jpg" alt="" style="width:1000px;">
<h2 class="formInfo">DEMO Conference Sign Up </h2>
<p class="formInfo">DEMO </p>
</div>
<BR/><!-- begin form -->
<form method=post enctype=multipart/form-data action=processors.php onSubmit="return validatePage1();"><ul class=mainForm id="mainForm_1">
<li class="mainForm" id="fieldBox_1">
<label class="formFieldQuestion">Company Name *</label><input class=mainForm type=text name=field_1 id=field_1 size='20' value=''></li>
<li class="mainForm" id="fieldBox_2">
<label class="formFieldQuestion">Guest Name * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Guest Name here</span></a></label><input class=mainForm type=text name=field_2 id=field_2 size='20' value=''></li>
<li class="mainForm" id="fieldBox_3">
<label class="formFieldQuestion">Contact Number * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Phone Number here </span></a></label><input class=mainForm type=text name=field_3 id=field_3 size='20' value=''></li>
<li class="mainForm" id="fieldBox_4">
<label class="formFieldQuestion">Email Address * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Email Address </span></a></label><input class=mainForm type=text name=field_4 id=field_4 size='20' value=''></li>
<input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value='2015'>
<li class="mainForm" id="fieldBox_6">
<label class="formFieldQuestion">Date of Arrival * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please select your date of arrival </span></a></label><select class=mainForm name=field_6 id=field_6><option value=''></option><option value="October 13 (Pre Conference)">October 13 (Pre Conference)</option><option value="October 14 (Day 1)">October 14 (Day 1)</option><option value="October 15 (Day 2)">October 15 (Day 2)</option><option value="October 16 (Final Day)">October 16 (Final Day)</option></select></li>
<li class="mainForm" id="fieldBox_7">
<label class="formFieldQuestion">Enter Your Arrival Time * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please Enter the Time you will be arriving to the airport </span></a></label><input class=mainForm type=text name=field_7 id=field_7 size='20' value=''></li>
<li class="mainForm" id="fieldBox_8">
<label class="formFieldQuestion">Date of Departure * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter the date you will be leaving the conference</span></a></label><select class=mainForm name=field_8 id=field_8><option value=''></option><option value="October 13 (Pre Conference)">October 13 (Pre Conference)</option><option value="October 14 (Day 1)">October 14 (Day 1)</option><option value="October 15 (Day 2)">October 15 (Day 2)</option><option value="October 16 (Final Day)">October 16 (Final Day)</option></select></li>
<li class="mainForm" id="fieldBox_9">
<label class="formFieldQuestion">Time of Departure * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please enter what time you will be departing the conference </span></a></label><input class=mainForm type=text name=field_9 id=field_9 size='20' value=''></li>
<li class="mainForm" id="fieldBox_10">
<label class="formFieldQuestion">Dinner October 14th * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Would you like to attend dinner with INFORM applications staff? </span></a></label><span><input class=mainForm type=checkbox name=field_10[] id=field_10_option_1 value="Yes" /><label class=formFieldOption for="field_10_option_1">Yes </label><input class=mainForm type=checkbox name=field_10[] id=field_10_option_2 value="No " /><label class=formFieldOption for="field_10_option_2">No </label></span></li>
<li class="mainForm" id="fieldBox_11">
<label class="formFieldQuestion">Dinner October 15th * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Would you like to attend dinner with members of the INFORM staff? </span></a></label><span><input class=mainForm type=checkbox name=field_11[] id=field_11_option_1 value="Yes " /><label class=formFieldOption for="field_11_option_1">Yes </label><input class=mainForm type=checkbox name=field_11[] id=field_11_option_2 value="No " /><label class=formFieldOption for="field_11_option_2">No </label></span></li>
<li class="mainForm" id="fieldBox_12">
<label class="formFieldQuestion">Do You Want To Attend The Comedy Show ? * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>A comedy show will be held at the Borgata on Wednesday the 14th </span></a></label><span><input class=mainForm type=checkbox name=field_12[] id=field_12_option_1 value="Yes " /><label class=formFieldOption for="field_12_option_1">Yes </label><input class=mainForm type=checkbox name=field_12[] id=field_12_option_2 value="No " /><label class=formFieldOption for="field_12_option_2">No </label></span></li>
<!-- end of this page --->
<!-- page validation -->
<SCRIPT type=text/javascript>
<!--
function validatePage1()
{
retVal = true;
if (validateField('field_1','fieldBox_1','text',1) == false)
retVal=false;
if (validateField('field_2','fieldBox_2','text',1) == false)
retVal=false;
if (validateField('field_3','fieldBox_3','menu',1) == false)
retVal=false;
if(retVal == false)
{
alert('Please correct the errors. Fields marked with an asterisk (*) are required');
return false;
}
return retVal;
}
//-->
</SCRIPT>
<!-- end page validaton -->
<!-- next page buttons --><li class="mainForm">
<input id="saveForm" class="mainForm" type="submit" value="Submit" />
</li>
</form>
<!-- end of form -->
<!-- close the display stuff for this page -->

It is not possible to store an PHP array in a MySQL database (because of it's type), but you can convert it to string and store this. Of course, you can convert this string later back to an array. You should change a database field to type LONGTEXT to store an array in it.
To store an array in text form, you can use serialize:
$arr = serialize($arr); // To save it in DB
$arr = unserialize($arr); // To get array after select
Or use JSON (better readable in database):
$arr = json_encode($arr); // To save it in DB
$arr = json_decode($arr); // To get array after select

Hey guys I just wanted to post the complete code encase anybody else is having trouble. I added the serialize function to my form processing part.
<?php
$where_form_is="http://".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9,field_10,field_11,field_12) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . $_POST['field_3'] . "','" . $_POST['field_4'] . "','" . $_POST['field_5'] . "','" . $_POST['field_6'] . "','" . $_POST['field_7'] . "','" . $_POST['field_8'] . "','" . $_POST['field_9'] . "','" . serialize($_POST['field_10']) . "','" .serialize($_POST['field_11']) . "','" .serialize($_POST['field_12']) . "')";
mysql_query($query);
mysql_close($link);
include("confirms.html");
?>
Strangely when you unserialize it. It just outputs the word array again.

Related

PHP - unable to get $_POST variables [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I am trying to make a posting system for a project I am working on. Problem is, for some reason, all $_POST values are null, even if they are supposed to be set. As a result, my PHP script does not work.
I can't tell why this is the case, as it was working fine just yesterday. How can I fix this?
<?php
function show_posts($posts, $parent_id = -1) {
$html = '';
if ($parent_id != -1) {
// If the posts are replies sort them by the "submit_date" column
array_multisort(array_column($posts, 'submit_date'), SORT_ASC, $posts);
}
$resultCount = 0;
// Iterate the posts using the foreach loop
foreach ($posts as $post) {
if (($_GET['search_query']) != "") {
if ($post['parent_id'] == $parent_id) {
if (strpos(implode($post), $_GET['search_query'])) {
$resultCount++;
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
ob_clean();
echo(strval($resultCount) . ' result(s) found for "' . $_GET['search_query'] . '"'); //display number of results
}
}
}
else
{
//add each post to HTML variable
if ($post['parent_id'] == $parent_id) {
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<h2></h2>
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
}
}
}
return $html;
}
// This function is the template for the write post form
function show_write_post_form($parent_id = -1) {
$rand = randomIdentifier(); //generate random identifier string
$html = '
<div class="write_post" data-post-id="' . $parent_id . '">
<form>
<h2 style="color: white;">New Post</h2>
<br>
<input name="parent_id" type="hidden" value="' . $parent_id . '">
<label for="name">Title:</label>
<input style="width: 100%;" id="name" name="name" type="text" placeholder="Enter a title..." required>
<br><br>
<label for="screenshot">Screenshot (if applicable):</label>
<input style="width: 100%;" id="screenshot" name="screenshot" type="url" placeholder="Screenshot URL">
<br><br>
<label for="type">URL:</label>
<input style="width: 100%;" id="url" name="url" type="url" placeholder="Download URL" required>
<br><br>
<label for="type">Description:</label>
<textarea name="content" id="content" placeholder="Write a description..." required></textarea>
<br><br>
<label for="type">Original Source (if known):</label>
<input style="width: 100%;" id="source" name="source" type="url" placeholder="Original Source URL">
<br><br>
<label for="type">Serial (if applicable):</label>
<input style="width: 100%;" id="serial" name="serial" type="text" placeholder="Serial">
<br><br>
<label for="name">Your Name/Nickname:</label>
<input style="width: 100%;" id="postauthor" name="postauthor" type="text" placeholder="Enter your name..." required>
<br><br>
<br>
<label for="type">Choose a type:</label>
<select name="type" id="type">
<option value="freeware">Freeware</option>
<option value="abandonware">Abandonware</option>
<option value="self-made">I wrote it myself</option>
</select>
<label for="category">Category:</label>
<select name="category" id="category">
<option value="app">App</option>
<option value="game">Game</option>
<option value="driver">Driver</option>
<option value="manual">Manual</option>
<option value="setup">Setup</option>
<option value="ROM">ROM</option>
<option value="other">Other</option>
</select>
<br><br>
<h2 style="color: white;">Post identifier string</h2>
<input name="identifier" id="identifier" style="width: 100%;" readonly="true" type="text"" value="' . $rand . '">
<br>
<p style="color: red;">This is your post identifier string. It can be used to delete this post in the future without having to contact an admin. <b>Make sure you do not lose it!</b></p>
<br><br>
<h2 style="color: white;">Make sure your submission meets the following criteria:</h2>
<br>
<p>๐Ÿ™‚ This submission is appropriate and doesn\'t have any mature content. - We want PPC Planet to be a safe place for people of all ages. Inappropriate submissions will be removed!</p>
<p>๐Ÿ‘ This submission is either freeware, abandonware, or self-made. - No piracy! It\'s not fair to the developer(s).</p>
<p>๐Ÿ’ป This submission has been tested, and works as advertised. - We don\'t want to have a bunch of broken software on the archive.</p>
<p>๐Ÿงพ This submission is not already on the archive. - Be sure that you are posting something unique!</p>
<p>๐Ÿ“ฑ This submission is related to Pocket PCs. - Remember, this is an archive of Pocket PC software.</p>
<br>
<p><b>By following these rules, we can make the archive a fun (and totally rad) place for everyone!</b></p>
<br><br>
<p style="color: red; font-size: xx-large; "><b>Make sure you have proofread your post, as you will not be able to edit it once it has been posted. Additionally, make sure you write your down identifier string somewhere if you have not already.</b></p>
<br><br>
<button type="submit">Create Post</button>
<br><br>
</form>
</div>
';
return $html;
}
if (isset($_GET['search_query'])) {
// Check if the submitted form variables exist
if (($_POST['name']).trim() != "") {
$stmt = $pdo->prepare('INSERT INTO posts (page_id, parent_id, name, screenshot, url, content, serial, type, category, identifier, source, postauthor, submit_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())');
$stmt->execute([ 1, $_POST['parent_id'], $_POST['name'], $_POST['screenshot'], $_POST['url'], $_POST['content'], $_POST['serial'], $_POST['type'], $_POST['category'], $_POST["identifier"], $_POST["source"], $_POST["postauthor"] ]);
exit('Your post has been submitted! You can reload the page to see it.');
}
else
{
// Get all posts by the Page ID ordered by the submit date
$stmt = $pdo->prepare('SELECT * FROM posts WHERE page_id = ? ORDER BY submit_date DESC');
$stmt->execute([ 1 ]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the total number of posts
$stmt = $pdo->prepare('SELECT COUNT(*) AS total_posts FROM posts WHERE page_id = ?');
$stmt->execute([ 1 ]);
$posts_info = $stmt->fetch(PDO::FETCH_ASSOC);
}
} else {
exit('No search query specified!');
}
function randomIdentifier() {
$pass = 0;
$complete = false;
while (!$complete)
{
//generate random identifier string until it is unique
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()';
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 100; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
include('mysqlconnect.php');
$pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
$data = implode($pass);
$stmt = $pdo->prepare( "SELECT identifier FROM posts WHERE identifier =:id" );
$stmt->bindParam(':id', $data, PDO::PARAM_STR);
$stmt->execute();
$myIdentifier = $stmt->fetch();
if (!$myIdentifier) {
//identifier is unique
$complete = true;
}
}
return $data;
}
?>
<?=show_write_post_form()?>
<?=show_posts($posts)?>
You can try it out for yourself here. All help is appreciated!
$_POST in PHP collects any variables submitted in the body of a HTTP POST request.
However your HTML form is submitting a GET request (which is the default if you don't specify the method). You can fix this by specifying the method attribute of the form:
<form method="post">
$_POST superglobal is only available in POST requests. You seem to be rendering your content in a GET request.

Getting the value of a checked radio PHP

The following code is the code i am using:
<form action="sendinfo.php" method="post" id="form">
-Title:<br>
<input type="text" class="u-full-width" name="title" placeholder="Insert a title" >
<br>-Date<br>
<input class="u-full-width" type="text" name="date" placeholder="Click to add a date"><hr>
<br>-Buildyear:<br>
<input class="u-full-width" type="text" name="buildyear" placeholder="click to add buildyear">
<br>-rebuild<br>
<input id="1" type="radio" name="rebuildyes" value="yes"><label for="1">tes</label>
<input id="2" type="radio" name="rebuildno" value="No"><label for="2">No</label><hr>
<input type="submit" value="send" class="u-full-width">
</form>
The other code is :
<?php
//variables
$title = $_POST['title'];
$date = $_POST['date'];
$buildyear = $_POST['buildyear'];
$rebuildyes = $_POST['rebuildyes'];
$rebuildno = $_POST['rebuildno'];
//in browser
echo "<h1>The inserted data has been locally stored as " . $title . " " . $date . ".txt</h1>";
echo "<p>click <a href='index.html'>Here</a> to return to the previous screen</p>";
//write text file.
$file = fopen($title . " " . $date . ".txt","w");
if ($date) fwrite($file, "Date: " . $date . "\r\n");
fwrite($file, "\r\n");
if ($buildyear) fwrite($file, "Buildyear: " . $buildyear . "\r\n");
if ($rebuildyes) fwrite($file, "Rebuild? " . $rebuildyes . "\r\n");
if ($rebuildno) fwrite($file, "Rebuild? " . $rebuildno . "\r\n");
?>
Result of this code is a generated text file with the data filled in in the form given on the first page. The problem here is that i can't get the radio buttons to work, atleast i can't get the data out of them. When they are empty they should not be written down in the file, when they are selected they should be.
Also, please dont tell me this is a dangerous way of coding PHP since i know it gives users acces to write where ever the PHP has acces to, but this "project" will only be accesable for a small amount of people and won't actually be hosted server wise. That being said if you have a better way for me building this project, not risk wise, just PHP wise, please tell me since i'm just starting coding PHP.
Thanks
<input type="radio" name="rebuild" value="yes"><label>Yes</label>
<input type="radio" name="rebuild" value="No"><label>No</label>
and get the value using
if(isset($_POST['submit'])){
echo $rebuild = $_POST['rebuild'];
die;
}
This is the code I tested, the file is written correctly and the value for "rebuild" is also correct :
<form action="sendinfo.php" method="post" id="form">
-Title:<br>
<input type="text" class="u-full-width" name="title" placeholder="Insert a title" >
<br>-Date<br>
<input class="u-full-width" type="text" name="date" placeholder="Click to add a date"><hr>
<br>-Buildyear:<br>
<input class="u-full-width" type="text" name="buildyear" placeholder="click to add buildyear">
<br>-rebuild<br>
<input id="1" type="radio" name="rebuild" value="yes"><label for="1">Yes</label>
<input id="2" type="radio" name="rebuild" value="no"><label for="2">No</label><hr>
<input type="submit" value="send" class="u-full-width">
</form>
PHP :
<?php
//variables
$title = $_POST['title'];
$date = $_POST['date'];
$buildyear = $_POST['buildyear'];
//in browser
echo "<h1>The inserted data has been locally stored as " . $title . " " . $date . ".txt</h1>";
echo "<p>click <a href='index.html'>Here</a> to return to the previous screen</p>";
//write text file.
$file = fopen($title . " " . $date . ".txt","w");
if ($date) fwrite($file, "Date: " . $date . "\r\n");
fwrite($file, "\r\n");
if ($buildyear) fwrite($file, "Buildyear: " . $buildyear . "\r\n");
if (isset($_POST['rebuild']) && $_POST['rebuild'] == 'yes') {
fwrite($file, "rebuild? yes \r\n");
}
elseif (isset($_POST['rebuild']) && $_POST['rebuild'] == 'no') {
fwrite($file, "rebuild? no \r\n");
}
fclose($file);
?>
Make your radio buttons a group :
<input id="1" type="radio" name="rebuild" value="yes"><label for="1">tes</label>
<input id="2" type="radio" name="rebuild" value="no"><label for="2">No</label><hr>
Then, check if the user selected the 'yes' value :
if (isset($_POST['rebuild']) && $_POST['rebuild'] == 'yes') {
// YOUR CODE
}

insert more than one array using one query

I want to insert an array of checkboxes, dropdowns, and dates into database. If I checked all the checkbox, all works fine. However, when I checked certain checkboxes, the value of checkboxes can be inserted but not the value of dropdown and date.
This is code for the checkbox, dropdown, and date:
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<input type='checkbox' id='spesimen$i' name='spesimen[]' value='$JenisSpesimen' required minlength='1'/><label>$JenisSpesimen</label><br>
</div>
<div class='select'>
<select id='bilangan$i' name='bilangan[]' class='med' style='display: none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<br>
<div class='input' id='tarikh_ambil$i' style='display: none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='tarikh_ambil_spesimen[]' class='small' readonly/>
</div>
</div>
</div>
And this the process:
$spesimen = $_POST['spesimen'];
$countSpesimen = count($_POST['spesimen']);
$bilangan = $_POST['bilangan'];
//$countBilagan = count($_POST['bilangan']);
$tarikh_ambil = $_POST['tarikh_ambil_spesimen'];
//$countTarikh = count($_POST['tarikh_ambil_spesimen']);
for ( $x = 0; $x < $countSpesimen; $x++)
{
$xx = $x+1;
$SubIDMohon = $IDMohonx.'-'.$xx;
$dd=substr($tarikh_ambil[$x], 0, 2);
$mm=substr($tarikh_ambil[$x], 3, 2);
$yy=substr($tarikh_ambil[$x], 6, 4);
$tarikh_ambil[$x] = $yy."-".$mm."-".$dd;
if($tarikh_ambil[$x] == '--') { $tarikh_ambil[$x] = '0000-00-00'; }
$pdo->exec("insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values ('".$IDMohonx."','".$SubIDMohon."','".$spesimen[$x]."','".$bilangan[$x]."','".$tarikh_ambil[$x]."','".$tarikh_hantar_spesimen."','".$tarikh_terima_spesimen."')");
}
I would recommend to wrap your fields into an common name, so that you can run a foreach over each 'fieldset' and then access its corresponding fields, instead of having them separate and independent as you have them now.
HTML would be something like this: (Implement the counter as you wish, but be sure to increment it before adding another set)
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<label><input type='checkbox' id='spesimen$i' name='fieldset[$counter][spesimen]' value='$JenisSpesimen' required minlength='1'/>$JenisSpesimen</label>
</div>
<div class='select'>
<select id='bilangan$i' name='fieldset[$counter][bilangan]' class='med' style='display:none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<div class='input' id='tarikh_ambil$i' style='display:none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='fieldset[$counter][tarikh_ambil_spesimen]' class='small' readonly/>
</div>
</div>
</div>
and your PHP code as follows:
foreach($_POST['fieldset'] as $i=>$fields){
$SubIDMohon = $IDMohonx .'-' . ($i + 1) ;
//If specimen is checked, the value comes with post, otherwise set it to default ''
$specimen = ( isset($fields['specimen']) ) ? $fields['specimen'] : '';
//check if the date is valid format
$date = '';
if(preg_match('^([0-9]{2}-){2}[0-9]{4}$', $fields['tarikh_ambil_spesimen'])){
$date = implode('-', array_reverse( explode('-', $fields['tarikh_ambil_spesimen']) ) );
}
else{
$date = '0000-00-00';
}
$pdo->exec(
"insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values (
'" . $IDMohonx . "',
'" . $SubIDMohon . "',
'" . $spesimen . "',
'" . $fields['bilangan'] . "',
'" . $date . "',
'" . $tarikh_hantar_spesimen . "',
'" . $tarikh_terima_spesimen . "'
)"
);
}
Try doing a print_r to your $_POST so you can see how it is structured.
Good luck!

PHP show data from Oracle database in a listbox

I want to show data from a Oracle database into a listbox.
, but I don't no how to do that.
Now I'm using a textbox and that works good.
This is my HTML code
<form name="form1" method="get" action="Get_opdracht.php"
Opdrachtnummer: <br /> <input id="Password1" type="number" name="nummer1" required="required"/>
<input type="submit" name="submit1" value="Zoeken" />
<hr />
</form>
PHP code (get_opdracht.php)
// database connect
$conn = oci_connect('username', 'password', 'connect');
// variable textbox
$username = $_GET['nummer1'];
// SELECT query
$array = oci_parse($conn, "SELECT * FROM OPD_VW, MDW_VW WHERE OPD_OPDRACHTNUMMER = '$username'");
$query = oci_execute($array);
//show data on page
while (($row = oci_fetch_array($array, OCI_BOTH)) != false) {
echo "<h1>Opdrachtnummer: " . $row['OPD_OPDRACHTNUMMER'] . "</h1><p> <b>Status: </b>" . $row['OPD_STATUS'] . "<p><b>Registratiedatum: </b>" . $row['OPD_REGISTRATIEDATUM'] . "<p><b>Einddatum: </b>" . $row['OPD_EINDDATUM'] . "<p><b>BTW tarief: </b>". $row['OPD_BTW_TARIEF'] . "<p><b>Totale contractsom: โ‚ฌ</b>" . $row['OPD_TOTALE_CONTRACTSOM'] . "<p><b>Percentage gerealiseerd: </b>" . $row['OPD_PERCENTAGE_GEREALISEERD'] . "%";
oci_free_statement($array);
oci_close($conn);
To create a listbox you need to use the select multiple as shown below.
<select name="myselect" multiple="multiple">
<option value="value">OPTION</option>
<option value="value">OPTION</option>
</select>

Inserting form array data into MySQL with PHP

I am fairly new to both PHP and MySQL and would appreciate some help with this one.
What I am trying to achieve: store a time sheet into a MySQL table using the form below which should post each day's data into a separate row while keeping the same employee name for each day entered. The user has the option to add additional days to the form -- a max of 7. I've tested everything without the use of arrays and am able to store data to the table without any problems.
HTML:
<form id="timesheet" method="post" action="timekeep.php">
<fieldset>
<h1>Employee Info</h1>
<ul>
<li>
<label>First Name:</label>
<input name="firstname" type="text">
</li>
<li>
<label>Last Name:</label>
<input name="lastname" type="text">
</li>
</ul>
</fieldset>
<fieldset>
<h1>Time Info</h1>
<h3>Day: 1</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
<h3>Day: 2</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
</fieldset>
<input id="submit" name="submit-time" type="submit" value="Submit Time">
</form>
PHP:
$sql_connection = mysql_connect($dbhost, $dbuser, $dbpass) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbuser, $sql_connection);
$sql = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (".
PrepSQL($date) . ", " .
PrepSQL($firstName) . ", " .
PrepSQL($lastName) . ", " .
PrepSQL($straightHours) . ", " .
PrepSQL($overtimeHours) . ", " .
PrepSQL($premiumHours) . ", " .
PrepSQL($totalHours) . ", " .
PrepSQL($perDiem) . "
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
Using PDO object would make this easier, mysql_ is legacy anyway:
$db = new PDO($hostname,$username,$password);
$qry = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (:date, :firstname, :lastname, :straighthours, :overtimehours, :premiumhours, :totalhours, :perdiem)"; // colon variables will be bound to actual variable
$statement = $db->prepare($query); //prevents injection
// binds variables to place holder in query
$statement->bindValue(':firstname', $firstname);
$statement->bindValue(':lastname', $lastname);
$statement->bindValue(':straighthours', $straighthours);
$statement->bindValue(':overtimehours', $overtimehours);
$statement->bindValue(':premiumhours', $premiumhours);
$statement->bindValue(':totalhours', $totalhours);
$statement->bindValue(':perdiem', $perdiem);
$statement->execute();
$statement->closeCursor();
you can do further input checking with php before passing anything to the sql via:
trim(strip_tags(htmlentities($firstname)));
PDO is a lot simpler to use and understand IMO
UPDATE:
tutorials on PDO
UPDATE #2:
For added functionality with arrays per day you can do:
<input type="text" name="firstname1">
// do this for all fields then
$workingday1 = array();
$workingday1['firstname'] = $_GET['firstname1'];
// etc. for all the other fields
Then you can access the field by:
$workingday1 = $_GET['workingDay1']; // or post or however you want to pass it
$firstname = $workingday['firstname'];
After that you can prune your database however you like. You can have a single table with all the values and edit your selects to display by employee or day or w/e. You can also have a table for each employee and then grab from those tables and display the data how ever you like.

Categories