insering HTML form data into MySQL database using PHP - html

I am just trying to figure out the logic behind inserting form data into the database. Below code (load.php) works fine. Howewer I receive somehow a syntax error in process.php, besides I'm not sure if my insert code is correct. I also doubt this code is secure, what is the key security factor that I should consider while working with databases? I know I ask many questions but I just try to get the whole picture. I would appreciate any advice and thoughts.
thanks!
**//process.php**
<?php
require ("load.php");
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$_POST[fname]','$_POST[lname]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**//load.php**
<?php
$servername = "localhost";
$database = "registration";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
**//index.php**
<?php require ("load.php"); ?>
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h3>Registration Form</h3>
<form name="registration" method="post" action="process.php">
<table border="0" cellspacing="2" cellpadding="2">
<tr><td>First Name:</td><td><input type="text" name="fname"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lname"></td></tr>
<tr><td> </td><td><input type="submit" name="submit" value="Register"></td></tr>
</table>
</form>
</body>
</html>

Try following code for process.php
This will works
require ("load.php");
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $lastname);
$fname= $_POST['fname'];
$lname= $_POST['lname'];
if ($stmt->execute()) {
echo "New record created successfully";
}
$stmt->close();

Related

HTML dropdown box with MySQL in form

I have PHP coding that works but I have had no luck transferring this to a HTML form. Any advise?
<?php
$db_host = "localhost";
$db_username = "combsb_combsb";
$db_pass = "pat60086";
$db_name = "combsb_sample";
#mysql_connect ("$db_host", "$db_username", "$db_pass") or die ("Could not connect to MySQL");
#mysql_select_db("$db_name") or die ("No Database");
Echo"Successful Connection";
$sql = "SELECT compname FROM Crew";
$result = mysql_query($sql);
echo "<select name='compname'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['compname'] . "'>" . $row['compname'] . "</option>";
}
echo "</select>";
?>
First I'd make sure to add the HTML boilerplate around your PHP. Then I think you mean mysql_fetch_row instead of mysql_fetch_array. Your final file should look something like:
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
// *Cut out for brevity, remember to paste back in*
$result = mysql_query($sql);
?>
<form action="" method="POST">
<?php
echo "<select name='compname'>";
while ($row = mysql_fetch_row($result)) {
echo "<option value='" . $row['compname'] . "'>" . $row['compname'] . "</option>";
}
echo "</select>";
?>
</form>
</body>
</html>
Post your output / errors next time or if this doesn't work

last insert id in pdo

I have a form with only one input. When I click the button, an AJAX request is made and the data is sent to the response.php, which uses the pdo library to insert the data to db. Here it is okay, but in the page, there is a success function which loads the data into the form - when the ajax request completes, the result is blank...I need to refresh(F5) the page to see the data ..
Here is this code:
<?php
include_once("config.php");
if (!empty($_POST)) {
try{
$statement = $conn->prepare("INSERT INTO DIAGNOSTICO (id_paciente, id_doctor, hconsulta) VALUES (?, ?, ?)");
if ($statement->execute(array($_POST['id_paciente'], $_POST['id_doctor'], $_POST['hconsulta'])));
$dbSuccess = true;
} catch (Exception $e) {
$return['databaseException'] = $e->getMessage();
}
{
echo $conn->lastInsertId();
echo '<li id="item_'.$row["id_diagnostico"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id_diagnostico"].'">';
echo '<img src="../images/icon_del.gif" border="0" />';
echo '</a></div>'; echo ' Fecha de consulta : ';echo $row["f_diagnostico"]; echo ' <br><br> ';
echo $row["hconsulta"].'</li>';
}
$dbh = null;
}
?>
It is working, but when in the page, the result returns from the ajax request and shows the id but not the data...I need the data result...can you help me?
best regards!
After using the lastinsertid you have to select data by using
$sth = $dbh->prepare("SELECT * FROM DIAGNOSTICO WHERE id_diagnostico= ".$conn->lastInsertId());
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
echo '<li id="item_'.$row["id_diagnostico"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id_diagnostico"].'">';
echo '<img src="../images/icon_del.gif" border="0" />';
echo '</a></div>'; echo ' Fecha de consulta : ';echo $row["f_diagnostico"]; echo ' <br><br> ';
echo $row["hconsulta"].'</li>';
Read http://php.net/manual/en/pdostatement.fetch.php

Use forms in wordpress which goes back to itself?

i'm working on a wordpress site using buddypress. So, i'm making a page where you can see members and search for them using a database: wp_users.
This works fine if i have it as a php when adding it to a wp page it shows up correctly but when clicking submit I get a 404 error.
This is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Search Contacts</title>
<style type="text/css">
#spacer {
border-top-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-top-style: solid;
}
</style>
</head>
<p><body>
<p> </p>
<form method="post" action="" id="searchform">
<p>
<input name="name" type="text">
<input type="submit" name="submit" value="Søk">
</p>
<p>Tips: du kan søke etter adresse, navn og e-post.</p>
</form>
<table width="600">
<tr>
<th width="200" height="50">Navn</th>
<th width="200"> </th>
<th width="200">E-post adresse</th>
</tr>
<?php
/* Change next two lines if using online*/
$db="skynnaks_skyn";
$link = mysql_connect('localhost', 'skynnaks_skyn', '*password*');
if (! $link) die(mysql_error());
mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT * FROM wp_users" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
if ($result) {
while ($row = mysql_fetch_array($result)) {
$_SESSION['id']=$row['id'];
#echo "<tr><a href='#'>".$row['display_name']."</a>";
echo "<td><a href="."/members/".$row['user_nicename']."/profile/>".$row['display_name']."</a></td>";
#echo "<a href=" '.$row['id'].'>Bruker: ".$row['user_url']."</a>";
echo "<td>".$row['user_url']."</td>";
echo "<td>".$row['user_email']."</td></tr>";
}
}
?>
</table>
<div id="spacer">
<?php
if(isset($_POST['submit'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "skynnaks_skyn", "*password*") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("skynnaks_skyn");
//-query the database table
$sql="SELECT ID, user_login, user_nicename FROM wp_users WHERE user_login LIKE '%" . $name . "%' OR user_nicename LIKE '%" . $name ."%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$loginName =$row['user_login'];
$niceName=$row['user_nicename'];
$ID=$row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "<a href="."/members/".$loginName."/profile/>".$niceName."</a>" ;
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
?>
</div>
<p> </p>
</body>
</html>
</p>
PS: I cant use default permalinks due buddypress plugin. And i know that buddypress comes with a members search, but i have installed norwegian language pack, but it wont work with members search in buddypress.
Thanks for the help :)
It looks like this problem,
so change your input tag name with any specific name attribute.
for example,
<input name="membername" type="text" />
but don't forget to get variable with same from $_POST

How can I get the row of a certain link in a table with data from a mysql database?

Here is my code:
<html>
<?php
DEFINE('DATABASE_USER', 'sfasdfasd');
DEFINE('DATABASE_PASSWORD', 'asdfasdfasdf');
DEFINE('DATABASE_HOST', 'sdfasdfasd');
DEFINE('DATABASE_NAME', 'dsafsdfasd');
$connect = mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) or
die ("Hey loser, check your server connection.");
mysql_select_db("minedb");
$query = "SELECT * FROM ideastable ORDER BY datee DESC";
$quey1="select * from ideastable";
$result=mysql_query($query) or die(mysql_error());
?>
<table border=1 style="background-color:#000000;" >
<caption><EM>Ideas List</EM></caption>
<tr>
<th>IDEAS</th>
<th>Thumbs Ups</th>
</tr>
<?php
while($row=mysql_fetch_array($result)){
echo "</td><td>";
echo $row['idea'];
echo "</td><td>";
echo $row['thumbsup'];
$i = $row['id'];
echo $i;
echo 'Thumbs Up!';
echo "</td></tr>";
}
echo "</table>";
?>
<SCRIPT type="text/javascript" src="jquery.min.js"></SCRIPT>
<SCRIPT type="text/javascript">
function doSomething() {
var myVar = "<?php echo $i; ?>";
alert(myVar);
$.load('uts.php?i=myVar');
return false;
}
</SCRIPT>
</html>
My question is how would I be able to make it so that when I click the Thumbs Up it recognizes the row the link was in? I am making a site where you can rate some of the objects in a database and that is the start up of it.
How about passing id to javascript function?
echo 'Thumbs Up!';

Creating a Combobox in HTML

Actually I have a CGI form which consists of textfields and I need a combobox in which I can enter my own data dynamically. May be it seems very silly question but I am new to cgi-perl as well as HTML so no idea what to do. Here is my form:
#!C:\perl\bin\perl.exe
use CGI;
use CGI qw/:standard/;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
my $q = new CGI;
use DBI;
use CGI qw(:all);
use strict;
use warnings;
print "Content-Type: text/html\n\n";
print $q->header ( );
if ( $q->param("submit") )
{
process_form ( );
}
else
{
display_form ( );
}
sub process_form
{
if ( validate_form ( ) )
{
display_form ( );
}
}
sub validate_form
{
my $User_Name = $q->param("User_Name");
my $User_Password= $q->param("User_Password");
my $User_Permission = $q->param("User_Permission");
my $User_Department= join(", ",$q->param("User_Department"));
my $error_message = "";
$error_message .= "Please enter your name<br/>" if( !$User_Name );
$error_message .= "Please enter your Password<br/>" if( ! $User_Password );
$error_message .= "Please Select a permission<br/>" if( !$User_Permission );
$error_message .= "Please select atleast 1 department<br/>" if(!$User_Department);
if ( $error_message )
{
display_form (
$error_message,$User_Name,$User_Password,$User_Permission,$User_Department);
return 0;
}
else
{
my $dbh = DBI->connect("dbi:SQLite:DEVICE.db","", "",{RaiseError => 1, AutoCommit =>
1 } );
my $sql = "SELECT COUNT(UserName) FROM UsersList WHERE UserName='$User_Name'";
my $sth = $dbh->prepare($sql) or die("\n\nPREPARE ERROR:\n\n$DBI::errstr");
$sth->execute or die("\n\nQUERY ERROR:\n\n$DBI::errstr");
my ($n) = $dbh->selectrow_array($sth);
$sth->finish();
if ($n > 0) {
print "Record Already Exists";
}
else {
my $sql = "INSERT INTO UsersList (UserName,Password,Permission,Department) VALUES
('$User_Name ',' $User_Password','$User_Permission','$User_Department')";
my $sth = $dbh->prepare($sql);
$sth->execute;
print "Record Added Successfully";
$sth->finish();
$dbh->commit or die $dbh->errstr;
}
$dbh->disconnect;
}
}
sub display_form
{
my $error_message = shift;
my $User_Name = shift;
my $User_Password = shift;
my $User_Permission= shift;
my $User_Department= shift;
my $User_Permission_Add_sel = $User_Permission eq "Add" ? " checked" : "";
my $User_Permission_Edit_sel =$User_Permission eq "Edit" ? " checked" : "";
my $User_Permission_Delete_sel =$User_Permission eq "Delete" ? " checked" : "";
my $User_Permission_View_sel =$User_Permission eq "View" ? " checked" : "";
my $User_Department_html = "";
my $dbh = DBI->connect("dbi:SQLite:DEVICE.db","", "",{RaiseError => 1, AutoCommit =>
1 } );
my $sql = "select DepartmentName from Departments order by DepartmentName";
my $sth = $dbh->prepare($sql);
$sth->execute() ;
while (my $User_Department_option= $sth->fetchrow_array)
{
$User_Department_html.= "<option value=\"$User_Department_option\"";
$User_Department_html.= " selected" if ( $User_Department_option eq
$User_Department );
$User_Department_html.= ">$User_Department_option</option>";
}
$sth->finish();
$dbh->commit or die $dbh->errstr;
print <<END_HTML;
<html>
<head><title>Form Validation</title></head>
<body>
<form action="AddUser.cgi" method="post">
<input type="hidden" name="submit" value="Submit">
<p>$error_message</p>
<TABLE BORDER="1" align="center">
<TR>
<TD>Name</TD>
<TD> <input type="text" name="User_Name" value="$User_Name"></TD>
</TR>
<TR>
<TD>Password</TD>
<TD colspan="2"><input type="password" name="User_Password" value="$User_Password"
size="20" maxlength="15" /></TD>
</TR>
<TR>
<TD>Role</TD>
<TD>"HERE I NEED A COMBOBOX"</TD>
</TR>
<TR>
<TD>Permission</TD>
<TD><input type="radio" name="User_Permission"
value="Add"$User_Permission_Add_sel>Add<input type="radio" name="User_Permission"
value="Edit"$User_Permission_Edit_sel>Edit<input type="radio"
name="User_Permission" value="Delete"$User_Permission_Delete_sel>Delete<input
type="radio" name="User_Permission" value="View"$User_Permission_View_sel>View</TD>
</TR>
<TR>
<TD>Department</TD>
<TD colspan="2"> <select name="User_Department" MULTIPLE
SIZE=4>$User_Department_html</select></TD>
</TR>
</TR>
<TR>
<TD align="center" colspan="2">
<input type="submit" name="submit" value="ADD">
</TD>
</TR>
</TABLE
</form>
</body></html>
END_HTML
}
What you're looking for here isn't done on the Perl side, but on the HTML+Javascript side. As noted by others, HTML does not have a built-in combo box form element. So, you're stuck with Javascript.
Personally, I like using JQuery whenever working with Javascript. It's a Javascript library which makes manipulating web pages elements much easier.
Specific to your question, you'll want to look at http://jqueryui.com/demos/autocomplete/ (there is an actual combobox demo linked on the right, if you really, really need a combobox instead of a Google-style autocomplete text field.
Not related to the combobox, but you might also want to look at Template::Toolkit - a templating system for Perl (and others) that will allow you to take the HTML out of your perl scripts. Believe me, having the HTML embedded in CGI scripts for anything beyond the most basic usages will turn into a nightmare soon enough.
In place of "HERE I NEED A COMBOBOX" you have to write :
<select name='User_Department' id='User_Department'>
$User_Department_html
</select>
However, you retrieve parameters within your sub display_form but you've never passed any.