I am trying to create a program that creates random registration keys and stores it in the database.If the user/customer already has a registration code it displays that key stored in the database in a text box on click 'else' it generates a new key and stores it in the database.The problem is i am not being able to store the key in the database.My code is:
<?php
if (isset($_POST['keygen'])){
$customer_no = $_POST['customer_no'];
$result = mysql_query("SELECT * FROM customer WHERE customer_no = '$customer_no'");
$row = mysql_fetch_array($result);
$keyString = $row['key'];
if($keyString == ""){
$keyString = generateRandomString();
$query = "UPDATE 'customer' SET key ='$keyString' WHERE customer_no = '$customer_no'";
mysql_query($query);
echo $keyString;
}
else{
echo $keyString;
}
}
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
?>
this is my HTML:
<div id="content" class="box2">
<div class="login">
<form action="" method="post" style="margin:12px;">
<table class="nostyle">
<tr>
<td align="center">
<label style="font-size:16px;"><strong>Customer ID: </strong></label>
<select name="customer_no">
<?php $result_customer= mysql_query('SELECT customer_no FROM customer ORDER BY customer_no'); ?>
<?php while($row_customer= mysql_fetch_assoc($result_customer)) { ?>
<option <?php if ($row_customer['customer_no']=='') { ?> selected="selected"<?php } ?>> <?php echo htmlspecialchars($row_customer['customer_no']); ?> </option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td align="center"><label style="font-size:16px;"><br /><strong>Register Key: </strong></label>
<input type="text" id="key" class="input-text" name="key" size="20" align="middle" value = " <?=$row["key"];?>"></td>
</tr>
<td align="center"><br /><input type="submit" id="keygen" class="input-submit" name="keygen" value="Generate" onclick=""/>
</td>
</tr>
</table>
</form>
</div>
</div>
I am a newbie, and am not that sure about the code.Please help!
You first have to do mysqli_connect. Look at http://php.net. Also you should use mysqli_ functions, since mysql_ functions are deprecated for newer versions of php.
Related
I have a form tag in which I have an input name and on click of a button, the value is displayed in table form. Now I want to update that value. How do I do it? This code does not have any database.
<form>
<input type="text" name="fname" value="" />
<input type="submit" value="submit" name="btn_submit" />
</form>
<br>
<br>
<table border="1">
<th>Name</th>
<th>Delete</th>
<th>Update</th>
<?php
session_start();
$na = array();
if (isset($_GET['btn_submit']))
{
if (isset($_SESSION['name']))
{
$na = $_SESSION['name'];
}
$na[] = $_GET['fname'];
$_SESSION['name'] = $na;
for ($i = 0; $i < count($na); $i++) {
?>
<tr>
<td><?php echo $na[$i]; ?></td>
<td>DELETE</td>
<?php
if(isset($_GET['del']))
{
}
?>
<td>UPDATE</td>
</tr>
<?php
}
}
?>
I need help on how to retain the entered values in the text fields where user entered the value after submit. I'm having difficulty trying to figure out how to retain the values, because when I click on the submit button, the page refreshes and then values gone, and I have to retype them again.
Below is my form:
<?php $count_name = count($x); ?>
<table>
<thead>
<tr>
<th colspan="<?php echo $count_name; ?>"><strong>MR</strong></th>
<th colspan="<?php echo $count_name; ?>"><strong>MS</strong></th>
</tr>
</thead>
<tbody>
<?php $_college = mysql_query("SELECT * FROM college");
if(mysql_num_rows($_college)) {
$i=0;
while($row_college=mysql_fetch_array($_college)) { ?>
<tr>
<?php for($j=0;$j<$count_name;$j++) { ?>
<td>
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
<td>
<?php } for($k=0;$k<$count_name;$k++) { ?>
<td>
<input type="text" name="ms<?php echo $k; ?>[]" value=""/>
<td>
<?php } ?>
</tr>
<?php } $i++;} ?>
</tbody>
<table>
<input type="hidden" value="<?php echo $count_name; ?>" name="totrows"/>
<input type="submit" value="Submit" name="submit"/>
Here's my code if button submit is click
<?php
if(isse($_POST['submit'])) {
$y = $_POST['totrows'];
$count_totcriteria = $y;
for($ab=0;$ab<$count_totcriteria;$ab++) {
$mr = 'mr_'.$ab;
$ms = 'ms_'.$ab;
$mr_score = $_POST[$mr];
$ms_score = $_POST[$mr];
foreach($mr_score as $key1 => $val1) {
if(is_numeric($val1) && !empty($val1)) {
$mr_val[] = $val1;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
foreach($ms_score as $key2 => $val2) {
if(is_numeric($val2) && !empty($val2)) {
$ms_str[] = $val2;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
}
}
I know I have to put some code in the 'value=""' in order to display back the entered values when form is submitted but I am not sure what code to use. Not sure how to catch each array values.
I think instead of
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
you are looking for something like this (assuming $i is your new outer loop)
<input type="text" name="mr_<?= $j ?>[<?= $i ?>]" value="<?= #$_POST['mr_'.$j][$i] ?>"/>
and the same change for the ms line.
Does that work?
I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"
I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);
i looking some help and nice attention here..
i bought some php script many years ago and now no suport anymore... i just want to add md5 to password field..
here my form:
<?php
$SQL = "SELECT * from USERS WHERE USERNAME = '$_SESSION[username]'"; $result = #mysql_query( $SQL ); $row = #mysql_fetch_array( $result );
include 'menu.php';
?>
<FORM METHOD="post" ACTION="?page=query_client">
<INPUT TYPE="hidden" NAME="controller" VALUE="USERS~update~account_details&up=1~<?php echo $row[ID]; ?>">
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Username</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<b><?php echo $row[USERNAME]; ?></b>
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Password *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="PASSWORD" NAME="PASSWORD" SIZE="40" VALUE="<?php echo $row[PASSWORD]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Email Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="EMAIL" SIZE="40" VALUE="<?php echo $row[EMAIL]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Full Name *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="FULLNAME" SIZE="40" VALUE="<?php echo $row[FULLNAME]; ?>">
</TD>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="ADDRESS1" SIZE="40" VALUE="<?php echo $row[ADDRESS1]; ?>">
</TD>
</TR>
<BR>
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdhead2" >
<DIV ALIGN="CENTER"><B>
<INPUT TYPE="submit" NAME="Submit" VALUE="Submit">
</B></DIV>
</TD>
</TR>
</TABLE>
</FORM>
and the
it self as query_client.php inside look like:
<?PHP
#session_start();
$controller = $_POST['controller'];
$pieces = explode("~", $controller);
$table = $pieces[0];
$qt = $pieces[1];
$return = $pieces[2];
$id = $pieces[3];
$hack = $pieces[4];
if ($qt == insert) $qt = 'INSERT INTO';
if ($qt == update) { $qt = 'UPDATE'; $end = "WHERE ID = '$id'"; }
$pre = array_keys( $_POST );
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
$count = count($pre); $count = $count - 2;
$sql = "$qt $table SET";
for ($i=0; $i < $count; $i++)
{
$x=$i+1;
$y = $_POST[$pre[$x]];
$d = $y;
mysql_query ("ALTER TABLE `$table` ADD `$pre[$x]` TEXT NOT NULL");
$sql .= " `$pre[$x]` = '$d',";
}
$sql .= " ID = '$id' $end";
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
if (empty($hack)) { } else {
$pieces = explode("/", $hack);
$h0 = $pieces[0];
$h1 = $pieces[1];
$h2 = $pieces[2];
$h3 = $pieces[3];
$h4 = $pieces[4];
$h5 = $pieces[5];
mysql_query ("ALTER TABLE `$table` $h0 $h1 $h2 $h3 $h4 $h5");
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
}
if (isset($_GET[inc])) include "$_GET[inc].php";
?>
so please help me how to add md5 in PASSWORD field?
thanks in advance..
Best to use a salt also - hashing and verification should be done at server - see secure hash and salt for PHP
Some links on writing secure code:
OWASP Top 10 for 2010
PHP Security: Fortifying Your Website
Writing Secure PHP