inserting values in to database only once - php

<?php if(isset($_POST['submit']))
{
$tadd=$_POST["tadd"]; //getting values
$pname=$_POST["pname"];
$date=$_POST["date"];
$result=mysql_query("insert into pannel(tadd,pname,date)values('$tadd','$pname','$date')");
echo "<script type='text/javascript'>
alert('Quotation Generated Successfully!')
</script>";
} ?>
<center>
<h1>Title</h1>
</center>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5"
cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date"
id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center"><input type="submit" name="submit"
value="submit"/></td> </tr></center> </table> </form>
I have one record in my database with
id tadd pname date
1 hello vvv 22/10/2014
if i insert values into database again it should data already inserted
please help me regarding this issue

You can achieve this using mysql_num_rows() which is one way to do this, which I believe the goal is to avoid duplicates.
Sidenote: You can also set your column(s) as UNIQUE to avoid duplicates.
N.B.: I used the pname column as an example. It's up to you to check which one will always be unique in regards to a username for instance.
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
}
Do sanitize your data:
$tadd = mysql_real_escape_string($_POST["tadd"]);
and do the same for the others.
Even better, use mysqli with prepared statements, or PDO with prepared statements.
They're much safer, because your present code is open to SQL injection.
Footnotes:
You should get rid of onSubmit="submit;" in your form. As outlined in comments, it's not going to do anything.
Edit:
<?php
// assuming DB connection has been made.
if(isset($_POST['submit'])) {
$tadd= mysql_real_escape_string($_POST["tadd"]);
$pname= mysql_real_escape_string($_POST["pname"]);
$date= mysql_real_escape_string($_POST["date"]);
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
exit;
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
echo "<script type='text/javascript'>alert('Quotation Generated Successfully!')</script>";
}
} // brace for if(isset($_POST['submit']))
?>
<!DOCTYPE html>
<head></head>
<body>
<center><h1>Title</h1></center>
<form method="post" action="">
<div align="center">
<center>
<table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5" cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date" id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center">
<input type="submit" name="submit" value="submit"/>
</td> </tr>
</table>
</center>
</div>
</form>
</body>
</html>

Related

MySQL table page not loading correct data

I'm creating a table that uses PHP to pull from a MySQL database that I have. I think I've got everything where I want it to be, however the only problem I'm having is that the results seem to be (for lack of a better word) "behind". What I mean by that is that my first page index.php is where I'm accepting user edits to the database. Once they click Update it sends them to my results.php file that is supposed to actually perform the SQL UPDATE and then display the updated table.
It updates the table just fine according to XAMPP's database editor. However, when I said "behind" I mean that the page loads, updates but doesn't display the updated data until either the user refreshes the page or returns to the first page THEN comes back. I'm not sure what could be causing it, so I'm hoping someone here can help me. I feel like the reason is something as simple as I'm just running the code in the wrong order, but I don't know for sure. My code is below:
index.php
<html>
<body>
<?php
include('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
?>
<form name="form1" method="post" action="results.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<input name="event_id[]" type="hidden" id="event_id" value="<?php echo $rows['event_id']; ?>">
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<input name="title[]" type="text" id="title">
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<input name="date[]" type="date" id="date">
</td>
<td align="center">
<input title="Use reference tables below to enter speaker ID" name="speaker[]" type="text" id="speaker">
</td>
<td align="center">
<input title="Use reference tables below to enter building ID" name="building[]" type="text" id="building">
</td>
<td align="center">
<input title="Use reference tables below to enter Room ID" name="room[]" type="text" id="room">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Update" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<html>
<body>
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
?>
<form name="form1" method="post" action="index.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<?php echo $rows['title']; ?>
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<?php echo $rows['event_date']; ?>
</td>
<td align="center">
<?php echo $rows['speaker_name']; ?>
</td>
<td align="center">
<?php echo $rows['building_name']; ?>
</td>
<td align="center">
<?php echo $rows['room_name']; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Return" value="Return"></td>
</tr>
</table>
</form>
</body>
</html>
Also if someone can give me some guidance as to how to run the htmlspecialchars function on my arrays within results.php I'd really appreciate it. I've already tried to create a for loop for literally each array but that didn't work. I've tried using ->
<?php
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
but that also didn't work, and I've tried using the array_walk_recursive but to no avail. I want to try and do something like W3Schools' example here W3Schools Form Validation towards the bottom of the page where it says Validate Form Data With PHP and then gives an example.
The result you get from the UPDATE query is the number of affected rows in your database. To correctly display the updated data, you need to re-fetch from the database before you generate the HTML. You should rearrange your code in results.php like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
Side note: If your data is sensitive, you may want to read about mysqli prepared statement so hackers cannot tamper with your queries.
Regarding your question about htmlspecialchars, see Stackoverflow "Execute htmlspecialchars on a multi level array".

How to Post some datas into mySQL server

I am trying to get some informations from users such as name midterm final grades and post them into database which I am using the MySQL server.
The problem is when I press the Add to DD button nothing changes and the data does not go into my table in database.
here is my main code:
<html>
<body>
<table border ="1">
<tr>
<td>Name</td>
<td><input id="name"> </input></td>
</tr>
<tr>
<td>Midterm</td>
<td> <input id="midterm"> </input></td>
</tr>
<tr>
<td>Final</td>
<td> <input id="final"> </input></td>
</tr>
<tr>
<td>Grade</td>
<td> <input id="grade"> </input></td>
</tr>
<td><input type="button" onclick="calculate()" value="Calculate"></td>
<td> <input type="submit" value="Add to DB"> </td>
</tr>
</table>
</body>
<script type="text/javascript">
function calculate(){
var mid=document.getElementById('midterm').value;
var fin=document.getElementById('final').value;
var grade=mid*(0.3)+fin*(0.7);
document.getElementById('grade').value=grade;
}
</script>
</html>
and this is also the code that inserts datas :
<html>
<body>
<form method="get" action="grade.php">
<input type="text" value="Welcome to Student Grades Calculator">
<br>
<input type="submit" value="GO">
</form>
</body>
</html>
<?php
$name=$_POST['name'];
$midterm=$_POST['midterm'];
$final=$_POST['final'];
$grade=$_POST['grade'];
echo 'Hey';
$connect= mysql_connect('localhost','root','','test');
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL:".mysql_connect_errno();;
}
$s = "INSERT INTO(name,midterm,final,grade) VALUES('rr','33','33','33')";
$sql = "INSERT INTO(name,midterm,final,grade) VALUES ('$name','$midterm','$final','$grade')";
mysqli_query($connect , $sql);
mysqli_close($connect);
?>
You need to set your variables to $_GETnot $_POST
$name=$_GET['name'];
$midterm=$_GET['midterm'];
$final=$_GET['final'];
$grade=$_GET['grade'];
I also recommend using post instead of get just for security

Can't echo data from phpmyadmin

Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet" href="box_style.css" />
</head>
<body>
<?php
include ("db_con.php");
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
while ($row_invoice=mysqli_fetch_array($run_query)){
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
}
?>
<div class='form'>
<form action="" method="post" enctype="multipart/form-data" >
<table width="745" align="center" border="2">
<p style="text-align: center;"><strong><span style="text-decoration: underline;">EDIT INVOICE:</span></strong></p>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Registration Number:</strong></td>
<td><input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/></td>
</tr>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Cost(Tshs):</strong></td>
<td><input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/></td>
</tr>
<tr>
<td colspan="6" align="center" bgcolor="#dbe5f1" ><input type="submit" name="update" class="submit-button" value="SAVE CHANGES"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Remove while loop from your php code since update is for one record based on id
The code will be as :
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
$row_invoice = mysqli_fetch_array($run_query);
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).
Put $reg_no above your isset($_GET...) check and set it null or empty string.
$reg_no = null;
if (isset($_GET['edit_invoice'])) {
// your code...
}
Edit: Do the same for $cost and $i_id ;)
PLEASE consider Tom Uddings comment with SQL injections!

Can't update/change data in MySQL from PHP

I was almost there, but the update is not functioning well especially on the bottom part.
<?php
require('dbconnect.php');//Connects to the database
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysqli_query($link,"SELECT username FROM members WHERE username='$user_check'");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
if(!isset($loggedin_session))
{
header("Location: login.php");
}//To ensure that you must be logged in to access this page
?>
<html>
<head>
<title>Healing Food Form</title>
<meta charset="iso-8859-1"> <!--charset specifies characters available-->
<meta name="author" content="Klarenz Kristoffer M. Qui;ntildeones">
<meta name="description" content="form to update healing food">
<meta name="keywords" content="healing food,form">
</head>
<body>
<?php
$id=$_GET['hf_id'];
$query = "SELECT * FROM healingfood WHERE hf_id='$id'";
if(!mysqli_query($link,$query))
{
die("Sorry. There's a problem with the query.");
}
//stores the result of the query
$result = mysqli_query($link,$query);
while($record = mysqli_fetch_assoc($result))
{
$hf_id=$record['hf_id'];
$hf_title=$record['hf_title'];
$a_id=$record['a_id'];
$hf_image=$record['hf_image'];
$hf_description=$record['hf_description'];
$hf_benefits=$record['hf_benefits'];
$hf_source=$record['hf_source'];
?>
<form action="updatehealingfood.php?hf_id=<?php echo $record['hf_id']; ?>" method="POST">
<table id="container" align="center">
<caption>Update healing food</caption>
<tr>
<td>Title:</td>
<td><input name="hf_title" type="text" value="<?php echo $hf_title; ?>"><br></td>
</tr>
<tr>
<td>Author ID:</td>
<td><input name="a_id" type="text" value="<?php echo $a_id; ?>"><br></td>
</tr>
<tr>
<td>Image URL:</td>
<td><input name="hf_image" type="url" value="<?php echo $hf_image; ?>"><br></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea name ="hf_description" rows="18" cols="60"><?php echo $hf_description; ?></textarea><br></td>
</tr>
<tr>
<td>Benefits:</td>
<td><input name="hf_benefits" type="text" value="<?php echo $hf_benefits; ?>"><br></td>
</tr>
<tr>
<td>Source:</td>
<td><input name="hf_source" type="text" value="<?php echo $hf_source; ?>"><br></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" name="update" value="Update Healing Food"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
}
$id=$_GET['hf_id'];
if(isset($_POST['update']))
{
$hf_title=$_POST['hf_title'];
$a_id=$_POST['a_id'];
$hf_image=$_POST['hf_image'];
$hf_description=$_POST['hf_description'];
$hf_benefits=$_POST['hf_benefits'];
$hf_source=$_POST['hf_source'];
$query2="UPDATE healingfood SET hf_title='$hf_title', a_id='$a_id', hf_image='$hf_image', hf_description='$hf_description', hf_benefits='$hf_benefits', hf_source='$hf_source' WHERE hf_id='$id'";
$result2=mysql_query($query2) or die();
echo "Updated";
}
?>
When I was supposed to update the data, the data remains the same. No one changed. I don't get the $id=$_GET['hf_id']; .
What are my errors?
You are mixing mysqli_* and mysql_*.
At the first part you use mysqli_query(), later you use mysql_query() which has no connection to the database yet.
Stick to mysqli_*.
Change:
$result2=mysql_query($query2) or die();
to:
$result2=mysqli_query($link, $query2) or die( "MySQL error: " . mysqli_error($link) );

PHP $_POST not updating

this is my code (full page: cust_edit.php):
<?
session_start();
ob_start();
include "../sql.php";
if (!$_SESSION['username']) {
#include "login.php";
} else {
#include "top.php";
?>
<?
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$text = $_POST['text'];
mysql_query("UPDATE custs SET name='$name', date='$date', text='$text' WHERE id='$id'");
echo '<p align="center"><b>Updated</b></p>';
}
$gid = $id;
if (!isset($gid)) {
$gid = addslashes($_GET['id']);
}
$query = mysql_query("SELECT * FROM custs WHERE id='$gid'");
$x = mysql_fetch_array($query);
echo '
<br />
<form name="f" action="cust_edit.php?id='.$x['id'].'" method="post">
<table border="0" cellspacing="1" width="100%">
<tr>
<td width="70%" id="submitright">
<input value="'.$x['name'].'" type="text" name="name" size="30" maxlength="50">
</td>
</tr>
<tr>
<td width="70%" id="submitright">
<input value="'.$x['date'].'" type="text" name="date" size="30" maxlength="50">
</td>
</tr>
<tr>
<td id="submitright">
<textarea class="ckeditor" name="text" dir="rtl" cols="80" style="width: 70%">'.$x['text'].'</textarea>
</td>
</tr>
<tr>
<td align="left" width="70%" id="submitright">
<input type="submit" value="Update">
</td>
</tr>
</table>
<input type="hidden" name="id" value="'.$gid.'">
</form>';
}
?>
<?
#include "bottom.php";
?>
my problem is that when i'm running this script - and updating the page - the pages is showing up normally and the details shown up in the inputs - but when i click the "Update" button, nothing happens - the page is refreshing but the lines:
mysql_query("UPDATE custs SET name='$name', date='$date', text='$text' WHERE id='$id'");
echo '<p align="center"><b>Updated</b></p>';
are not running for some reason, can someone help me with that?
<input type="submit" value="Update">
replace with
<input type="submit" name="submit" value="Update">
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
And also as others have mentioned don't use php short open tag. It will not support since PHP 5.4 and onward. Most of time it has discussed here also, php short_open_tag problem
Some webservers will not accept <?. Use <?php instead.
Use mysqli (MySQL Improved Extension) instead of mysql
Your submit don't have name attribute <input type="submit" name="submit" value="Update">. OR....
You can replace this line:
if (isset($_POST['submit'])) {
on this
if (isset($_POST['id'])) {

Categories