Posting to Database with PHP - php

I'm trying to all users to add data to a database. However, it's not working and I'm not getting an error. This is purely for practice, but it's still frustrating. Thoughts?
<form name="Add" id="Add" method="post" action="programadd.php">
<p>Content Name:
<input name="program" type="text" id="program" style="width: 500px; height: 20px;" />
</p>
<p>Content Air Date
<input name="airdate" type="date" id="airdate" />
</p>
<p>Description
<input name="description" type="text" id="description" style="width: 500px; height: 20px;" />
</p>
<p>Production
<input name="production" type="text" id="production" value="nothing" style="width: 500px; height: 20px;" />
</p>
<p>Promotions
<input name="promotion" type="text" id="promotion" value="nothing" style="width: 500px; height: 20px;" />
</p>
<p>Community
<input name="community" type="text" id="community" value="nothing" style="width: 500px; height: 20px;" />
</p>
<p>Web
<input name="web" type="text" id="web" value="nothing" style="width: 500px; height: 20px;" />
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
Here's the programadd page. Thanks!
<?php
include('connect-db.php');
$program = $_POST['program'];
$airdate = $_POST['airdate'];
$description = $_POST['description'];
$production = $_POST['production'];
$promotion = $_POST['promotion'];
$community = $_POST['community'];
$web = $_POST['web'];
if (mysql_query ("INSERT INTO calendar(program, airdate, description, production, promotion, community, web) VALUES
('$program', '$airdate', '$description','$production', '$promotion', '$community', '$web')"))
{ echo "Content successfully added to the database. <br />
}
else {
die(mysql_error());
}
require_once("db_connx_close.php");
?>

{ echo "Content successfully added to the database. <br />
^---missing " here
If you're NOT getting a syntax error from this, then you're probably running with display_errors and error_reporting turned off. NEVER have them disabled when you're developing. It's the coding equivalent of stuffing your fingers in your ears and going "lalalala can't hear you don't care what you have to tell me lalala".

This may be an error in your question's markdown, but just incase it isn't I will mention what I am seeing.
You are not closing the string on the echo after your query:
echo "Content successfully added to the database. <br />
Should be:
echo "Content successfully added to the database. <br />";
Also, just for the sake of clarity, you are using $_POST data directly in a SQL Query without sanitizing or validating the data. I realize this is for practice but it should be mentioned that this methodology is highly vulnerable to SQL Injection and will make your database easily accessible. You could, instead, use PHP's PDO Library for your connections or at the very least sanitize your inputs.

However your code is vulnereble to sql-injection although for your help put this change in your query syntax like this--
if (mysql_query ("INSERT INTO calendar(program, airdate, description, production, promotion, community, web) VALUES ('".$program."', '".$airdate."', '".$description."','".$production."','".$promotion."', '".$community."', '".$web."')"))
{
echo "Content successfully added to the database. <br />";
}

Related

update mysql as user updates textbox value

i want to update value(s) as a student change value(s) in correction or update form.
till know i'm able to fetch and display values in text boxes on the bases of name selected from dropdown list from data base using ajax and json. but when i try to update database it do not works...
HTML:
<select name="u_stu" id="u_stu" onchange="show(this.value);" style="float:right; height:30px; width:180px;">
<option selected="selected" disabled="disabled">Choose</option>
<option>stu1</option>
<option>stu2</option>
<option>stu3</option>
</select>
name: <input type="text" id="name" name="name" style="float:right; height:20px; width:200px;"/><br /><br />
age: <input type="text" id="age" name="age" style="float:right; height:20px; width:200px;" /><br /><br />
phone: <input type="text" id="phone" name="u_ver_txt" style="float:right; height:20px; width:200px;" /><br /><br />
address: <input type="text" id="add" name="add" style="float:right; height:20px; width:200px;" /><br /><br />
hobby: <input type="text" id="hobby" name="hobby" style="float:right; height:20px; width:200px;" /><br /><br />
<input type="submit" value="Submit" name="u_s2" id="u_s2" style="position:relative; top:-180px; "/>
MYSQL PHP
<?php
$c=mysql_connect("localhost","abc","xyz");
mysql_select_db("root");
if(isset($_POST['u_s2']))
{
$name=$_POST["name"];
$age=$_POST["age"];
$phone=$_POST["phone"];
$address=$_POST["address"];
$hobby=$_POST["hoddy"];
$id=$_POST["u_id"];
$q2="UPDATE student SET
name=$name,age=$age,phone=$phone,address=$address,hobby=$hobby WHERE Sr. no=$id";
mysql_query($q2);
}
?>
You need something like this:
$q= "update student set name = '".$name."', age = '".$age."', phone = '".$phone."', address = '".$address."', hobby = '".$hobby."' WHERE user = 'the user id'";
You should use a WHERE statement as well like the above example so that you can be sure that you are updating the correct row.
You should also consider using mysql_real_escape_string function:
$name = mysql_real_escape_string($_POST['name']);
http://php.net/manual/en/function.mysql-real-escape-string.php
If this will be an updating form you should also include the value in the input fields and etc. so they will see the values and update what they need.
I also suggest that you use mysqli functions instead of mysql functions as mysql is no longer supported and deprecated.

PHP DOM - Getting contents UNDER strong tag

I am attempting to learn DOM for PHP. There does not seem to be alot of tutorials out there for learning the HTML queries. So I ask this question:
I have ran the following code:
<?php
function DOMinnerHTML($element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($child, true));
$innerHTML.=trim($tmp_dom->saveHTML());
}
return $innerHTML;
}
$doc = new DOMDocument();
#$doc->loadHtmlFile("http://******/business_analyst");
$x = new DOMXpath($doc);
foreach ($x->query("//div[#class='content']") as $node)
{
echo DOMinnerHTML($node);
}
?>
And this returns the following:
<div class="content">
<p>
<span class="green"> | Elizabethtown Headquarters</span>
</p>
<p><strong>Summary</strong><br />
Working with Microsoft SQL Server, evaluate and utilize reporting tools, and work closely with other departments to determine business needs.</p>
<p><strong>Responsibilities</strong></p>
<ul>
<li>Communicate with other functional departments such as Finance, Sales/Marketing, Customer Service, Support Services and other departments to identify business needs.</li>
<li>Gather and formalize business requirements such as for reports, data extracts, third-party vendor application enhancements and internal application development.</li>
<li>Create simple and advanced queries using SQL structured for MS SQL Server.</li>
<li>Evaluate and utilize third-party reporting tools as needed depending on the required solution.</li>
<li>Perform database administration tasks as needed such as creating scheduled batch scripts, monitoring database performance and evaluating backup processes.</li>
<li>Prepare technical and user documentation as needed.</li>
<li>Write scripts and stored procedures as needed.</li>
<li>Work as part of a team to exchange business and technical knowledge in a positive manner.</li>
<li>Perform other duties as required related to analysis, requirements and database related projects.</li>
</ul>
<p><strong>Requirements</strong></p>
<ul>
<li>Minimum 3 years working with Microsoft SQL Server.</li>
<li>Minimum 3 years developing simple and complex SQL queries using MS SQL Server.</li>
<li>Experience writing batch scripts, stored procedures and stored functions.</li>
<li>Experience with business analysis related desktop tools such as Excel and Word.</li>
<li>Experience with third-party reporting tools.</li>
<li>Experience tuning SQL Server databases a plus.</li>
<li>Oracle and MySQL database experience a plus.</li>
<li>Professional attitude and willingness to work independently and as a member of a team.</li>
<li>A.S. Degree and/or B.S. Degree preferred but not required depending on years of experience.</li>
</ul>
<h2>Apply Now</h2>
<form class="careers-form" id="business_analyst" method="post" action="http://web1.bluegrasscellular.com/" enctype="multipart/form-data" >
<div class='hiddenFields'>
<input type="hidden" name="ACT" value="20" />
<input type="hidden" name="URI" value="about/careers/business_analyst" />
<input type="hidden" name="XID" value="" />
<input type="hidden" name="status" value="open" />
<input type="hidden" name="return" value="/contact/thanks/%%entry_id%%" />
<input type="hidden" name="redirect_on_duplicate" value="" />
<input type="hidden" name="RET" value="http://web1.bluegrasscellular.com/about/careers/business_analyst" />
<input type="hidden" name="form_name" value="careers" />
<input type="hidden" name="ajax_request" value="y" />
<input type="hidden" name="params_id" value="13930914" />
<input type="hidden" name="site_id" value="1" />
</div>
<fieldset>
<input type="hidden" name="job_title" value="Business Analyst" />
<input type="hidden" name="job_description" value="Business Analyst" />
<input type="hidden" name="source" value="website-careers" id="source">
<input type="hidden" name="message" value="0bba03eb0000000000000000000000071a5c" id="message">
<input type="hidden" name="job_location" value="Elizabethtown Headquarters" />
<label><span class="red">*</span>Name:</label>
<input type="text" name="name" /><br />
<label><span class="red">*</span>Email:</label>
<input type="text" name="email" /><br />
<label><span class="red">*</span>Resume:</label>
<input type="file" name="file1" />
<label><span class="red">*</span>Please enter the text as it appears in the box below</label>
<script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
window.onload = function(){
Recaptcha.create('6LduXdcSAAAAAEjc_hSNGCFG-BurosYW8a49xmgv',
"recaptcha_container",
{
theme:'red',
lang:'en'
}
);
};
</script>
<div id="recaptcha_container"></div>
<div class="float-clear enews-optin">
<input class="check" style="display: inline; float:left; width: 16px; margin-right: 8px;" type="checkbox" name="enews" value="yes"/>
<label class="check" style="display: inline; padding: 1px; margin: 0; float: left;">Yes, sign me up to receive email updates from Bluegrass Cellular with information on the latest products, services, special offers and discounts.</label>
</div>
<input class="submit-btn" type="submit" /><br>
<p class="float-clear"><small><span class="red">*required</span></small></p>
</fieldset>
</form>
<p>Back to Jobs</p>
</div><!-- /.content-->
I am wanting to grab the contents under the strong headings (Summary, Responsibilities, Requirements). Since I cannot seem to find very much help online about this I am asking for your help here! Thanks!
If all you want is just the contents of the <strong> nodes, just update your XPath query to the following:
//div[#class='content']//strong/text()
You can also retrieve the <strong> nodes with
//div[#class='content']//strong
and then retrieve the values from within PHP.

Preserve form values on validation

Ik want to prevent field reset after validation. I have searched some topics but i cant implement it in my code.
if($form_view == true) {
echo '';
if($error != '') {
echo '<strong><font color="#FF0000">Fout:</font></strong><br />'.$error.'<br />';
}
echo '<form method="POST" action="'.$filename.'" style="border:0px; margin:0px; padding:0px;">
Voornaam
<br />
<input type="text" name="voornaam" maxlength="50" id="input_contact" style="width: 200px; value="'.(isset($_POST['voornaam']) ? $_POST['voornaam'] : '').'">
<br />
Achteraam
<br />
<input type="text" name="achternaam" maxlength="50" id="input_contact" style="width: 200px; value="'.(isset($_POST['achternaam']) ? $_POST['achternaam'] : '').'">
<br />
Adres
<br />
<input type="text" name="adres" maxlength="50" id="input_contact" style="width: 400px; value="'.(isset($_POST['adres']) ? $_POST['adres'] : '').'">
<br />
Postcode <h7><i><small>(1234 AB)</small></i></h7>
<br />
<input type="text" name="postcode" maxlength="7" id="input_contact" style="width: 100px; value="'.(isset($_POST['postcode']) ? $_POST['postcode'] : '').'">
<br />
Woonplaats
<br />
<input type="text" name="woonplaats" maxlength="50" id="input_contact" style="width: 200px; value="'.(isset($_POST['woonplaats']) ? $_POST['woonplaats'] : '').'">
<br />
Telefoonnummer <h7><i><small>(0123-456789)</small></i></h7>
<br />
<input type="text" name="telefoonnummer" maxlength="11" id="input_contact" style="width: 100px; value="'.(isset($_POST['telefoonnummer']) ? $_POST['telefoonnummer'] : '').'">
<br /><br />
If you can give me one example on how to implement this in one field.
Thanks a lot
If the post is not made to this specific page they're landing on then the $_POST variable will not contain that information.
The quick and dirty of it is to save the information submitted in the $_SESSION[] as an array.
When the form is submitted, in addition to doing whatever you're currently doing, you need to save the information submitted into the session on the receiving script.
if ($_POST['submit']) {
// repeat or configure as desired to save submitted fields into Session
$_SESSION['form_info']['email_address'] = $_POST['email_address'];
}
On the form page itself you would use the following
if (isset($_SESSION['form_info'])) {
// You'll want to most likely consider filtering these using appropriate functions.
<input type="text" name="email_address" maxlength="50" id="email_address" style="width: 200px; value="<?php if (isset($_SESSION['form_info']['email_address']) { $_SESSION['form_info']['email_address']; } ?>">
}
Is the form action variable $filename referring to this particular php file or somewhere else where validation happens? If the form action happens somewhere else, the Moylin's answer is your solution (using $_SESSION). Otherwise, if possible, it's reasonable and simple to do the validation right here. echoing $_POST to value fields, as you did, should be sufficient enough (you dont even need the ternary operation there, if you want short code).
<form method="POST" action="thisPhpFile.php" >
value ="'. #$_POST['voornaam'] .'"
In the validation part (before echoing the form), you naturally want to check for all the errors, required fields etc. If everything is valid just point user to wanted location. Something along these lines:
if(isset($_POST['mySubmit'] {
//check errors/validate
if($valid == true) {
Header("Location: yourLocation.php");
}
}
else {
//echo your form here
}

Unable to Style Div

Creating a blog from scratch is a difficult process but I've been plodding along with some minor issues which have been resolved. My minor issue today is the fact that I'm unable to style the site background with an image. I'm able to add colors but not an image.
The second minor issue is to do with my Div tags. I've created a basic form that submits comments to my MySQL database but when I attempt to style the div that I've enclosed the form and comments that are displayed the styles have not appeared. I have included my Comments CSS below and my post.php page.
CSS:
#comments-title {
background-color: #282828;
width: 567px;
height: 30px;
font-size: 25px;
font-family: arial;
color: #ffffff;
padding: 5px;
padding-top: 6px;
padding-bottom: 4px;
}
#comment-list{
border:1px solid #dadada;
width: 567px;
padding: 5px;
}
PHP:
<h2 id="comments-title">Comments</h2>
<div id="comment-list'">
<?php
}
$commenttimestamp = strtotime("now");
$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$timestamp = date("l F d Y", $row['timestamp']);
print("<p id='comment'>" . stripslashes($row['comment']) . "</p>");
printf("<p id='comment'>Comment by %s # %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
}
?>
<form method="post" action="process.php">
<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />
<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">
<strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="25" /><br />
<strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="25" /><br />
<strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="25" value="http://" /><br />
<strong><label for="comment">Comment:</label></strong><br />
<textarea cols="25" rows="5" name="comment" id="comment"></textarea></p>
<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>
</form>
</div>
Take a second look at this line:
<div id="comment-list'">
See that little ' in there? Take it out.
For everything else, you're going to have to be more specific. You've basically posted a large slab of code here without pointing to the offending code.
Remember that the ID have to be unique. use class instead if id. (In your while loop: <p id='comment'>, you have multiple id's with the same id.
You have a lot of this to fix.
And, try to validate your code to check for some errors that might prevent it from working. http://validator.w3.org
+ You have a single quote in your comment-list ID

Cannot interact with checkbox in FireFox or Chrome. Works in IE

Here's the code:
<div id="regpage">
<form action="" method="post">
<fieldset style="border:none;">
<div class="label">Username:</div> <input type="text" name="username" class="item" value="" /><br />
<div class="caption">Must be 5-15 characters</div><br />
<div style="clear:both;"></div>
<div class="label">Password:</div> <input type="password" name="password" class="item" value="" /><br />
<div class="caption">Must be 6-20 characters</div><br />
<div style="clear:both;"></div>
<div class="label">Email:</div> <input type="text" name="email" class="item" value="" /><br />
<div class="caption">Valid email address is required</div><br />
<div style="clear:both;"></div>
<input name="terms" type="checkbox" id="terms" value="agree" /><div class="caption2"><label for="terms">I agree to the terms and conditions</label></div>
<p><input type="submit" name="register" value="Register" id="register" style="float:left;border:1px solid #999;background:#E4E4E4;margin-top:5px;" /></p><br />
</fieldset>
</form>
</div>
And the id "regpage" is definded in the style.css as:
#regpage {
width: 356px;
height: 150px;
color: #000000;
font-family: "Tahoma", Arial, Helvetica, sans-serif;
font-size: 13px;
}
If I move the checkbox OUT of <div id="regpage"> it works just fine. But inside it will not interact in Mozilla. I've even tried adding onclick='this.checked="checked"' and it still does not interact. You can click until your blue in the face and nothing will happen.
What's the deal! This is REALLY driving me batty.
I don't see any problem: http://jsfiddle.net/cXRPd/ (Firefox 3.0.19)
Found it myself: My div's height wasn't set high enough. It didn't expand enough to cover the checkbox.
Setting the height to 250 fixed the problem.
My overflow is set to hidden, but apparently it still blocked the ability to interact with the box.

Categories