Insert 1 row but shows 3 rows - php

I just want to insert one row with my form but MySQL is showing 3 rows, one of them is mine and two of them is just null.
Here is my code.
Form
<form method="post" id="contactform" action="iletisim-basarili.php">
<input type="text" name="isim" placeholder="İsim" class="formcontact"><br>
<input type="text" name="soyisim" placeholder="Soyisim" class="formcontact"><br>
<input type="text" name="telefon" placeholder="Telefon Numarası" class="formcontact"><br>
<input type="text" name="eposta" id="eposta" placeholder="E-Posta Adresi" class="formcontact"><br>
<input type="text" name="konu" id="konu" placeholder="Konu" class="formcontact"><br>
<textarea type="text" name="mesaj" id="mesaj" rows="8" placeholder="Mesajınız" class="form--contact--textarea"></textarea><br>
<div class="validred"></div><br>
<input type="submit" name="submit" class="button-form" value="Formu Gönder" />
</form>
PHP
<?php
require ('config.php');
$isim = trim( $_POST['isim']);
$soyisim = trim( $_POST['soyisim']);
$telefon = trim( $_POST['telefon']);
$eposta = trim( $_POST['eposta']);
$konu = trim( $_POST['konu']);
$mesaj = trim( $_POST['mesaj']);
$kaydet = mysql_query( "INSERT INTO contact SET
isim = '$isim',
soyisim = '$soyisim',
telefon = '$telefon',
eposta = '$eposta',
konu = '$konu',
mesaj = '$mesaj'
");
if( mysql_affected_rows()) {
echo "<h3 class='green'>destek talebini kaydettik.</h3><br><h4 class='text'>en kısa sürede"." <b>$destekmail</b>"." üzerinden seninle iletişime geçeceğimizden hiç şüphen olmasın.</h4>";
}
?>

This is function check wather submit button press or its self posted page.So you need to check for submit button.
<?php
require ('config.php');
//Check before form is submitted.
if(isset($_POST['submit'])){
$isim = trim( $_POST['isim']);
$soyisim = trim( $_POST['soyisim']);
$telefon = trim( $_POST['telefon']);
$eposta = trim( $_POST['eposta']);
$konu = trim( $_POST['konu']);
$mesaj = trim( $_POST['mesaj']);
$kaydet = mysql_query( "INSERT INTO contact SET
isim = '$isim',
soyisim = '$soyisim',
telefon = '$telefon',
eposta = '$eposta',
konu = '$konu',
mesaj = '$mesaj'
");
if( mysql_affected_rows()) {
echo "<h3 class='green'>destek talebini kaydettik.</h3><br><h4 class='text'>en kısa sürede"." <b>$destekmail</b>"." üzerinden seninle iletişime geçeceğimizden hiç şüphen olmasın.</h4>";
}
}
?>

Related

Adding an image into a database using a html form

I am trying to add records into a database. Each record has a corresponding image. The records are getting inserted into the database but it is not working for the image. I am getting this error "connected succesfully
Notice: Undefined variable: sql in C:\xampp\htdocs\Syokimaufc\addplayer.php on line 35
Error: Query was empty" How can i solve this?
HTML form
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<p> Photo: <input type="file" name="image"/></p>
<input type="submit" value="submit"/>
<form/>
php script
<?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
if (isset($_POST['submit']))
{
$imageName = mysql_real_escape_string($_FILES ["image"]["iname"]);
$imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["iname"]);
if (substr($imageType,0,5) == "image")
{
$sql = "INSERT INTO players ( playerid, name, age, position, nationality, iname, image ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality', '$imageName', '$imageData' )";
}
else
{
echo "only images are allowed";
}
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
in your form try adding an attribute:
<form enctype="multipart/form-data">
......
..
</form>
Have you tried it with the name property in the submit ?, it seems that is not going to "if"
<input type="submit" name="submit" value="submit"/>
just check following steps:
In html file, a form with image upload should be set with enctype="multipart/form-data"
e.g. <form enctype="multipart/form-data>
In PHP script
$_FILES["image"]["iname"] is wrong.
$_FILES["image"]["name"] should be the right one.

MySQL Add not picking up one field

I am doing a project to add, update, delete, etc records from a p2pmyadmin database.
I am working on the current code. When update is hit, all the fields update in the database, except the 'Surname' field. I cannot figure out why... Can anyone advise?
$dirtyPassword = $_POST['frmPassword1'];
if (isset($_POST['formName']) && $_POST['formName'] == "addUser") {
if ( ($_POST['frmSurname'] != '') &&
($_POST['frmEmail'] != '') &&
($_POST['frmPassword1'] != '') ) {
if ($_POST['frmPassword1'] != $_POST['frmPassword2'] ) {
echo "Passwords do not match!";
//Clean form values
$cleanFirstName = mysqli_real_escape_string($db, $_POST['frmName']);
$cleanSurname = mysqli_real_escape_string($db, $_POST['frmSurname']);
$cleanEmail = mysqli_real_escape_string($db, $_POST['frmEmail']);
//Clean password
$password = sha1(mysqli_real_escape_string($db, $_POST['frmPassword1']));
// Build username
$username = strtolower($cleanFirstName.substr($cleanSurname,0,1));
$dateTime = date('Y-m-d g:i:s',time());
// Check email is unique
$QryEmail = "SELECT *
FROM registeredUsers
WHERE EmailAddress = '$cleanEmail'";
$chkEmail = mysqli_query($db,$QryEmail);
$numChkRowsE = mysqli_num_rows($chkEmail);
// Check Username is unique
$QryID = "SELECT *
FROM registeredUsers
WHERE UserName = '$username'";
$ChkID = mysqli_query($db,$QryID);
$numChkRowsI = mysqli_num_rows($chkID);
//check that zero records returned (no duplicates)
if ($numChkRowsE == 0 && $numChkRowsI == 0){
//Query
$query = "INSERT INTO registeredUsers VALUES(NULL, '$username', '$cleanFirstName', '$cleanSurname', '$cleanEmail', '$password', '$dateTime', 0) ";
$insQry = mysqli_query($db,$query);
if ($insQry) {
/* SUCCESS */
$_SESSION['success'] = 'Registration successful';
header("Location:project-users-manage.php");
exit;
} else {
/* FAIL */
}
}
}
?>
<fieldset style =width:30%>
<form method="post" action="">
<p>
First Name : <input type="text" name="frmName" value="" placeholder='First Name'><br>
Surname: <input type="text" name="frmSurname" value="" placeholder='Surname'><br>
Email Address: <input type="text" name="frmEmail" value="" placeholder='Email Address'><br>
Password: <input type="password" name="frmPassword1" value="" placeholder='Password'><br>
Repeat Password: <input type="password" name="frmPassword2" value="" placeholder='Password Again'><br>
<input type="submit" name="Register" value="Register">
<input type='hidden' name='formName' value='addUser' />
</p>
</form>
<br>
<a href='project-users-manage.php'>User Management</a>
<a href=''>Logout</a>

Update SQL data within PHP

Ok i have updated my Code, not getting any Errors but nothing is being updated on the mysql side nor on the PHP Front end.
I have even tried a Hard Coded Statment.
This section is at the Very top of my Php Viewer page..
<?php
/
/ IF RESQUEST IS EQUAL TO SUBMUIT
if (isset($_REQUEST['submit']))
{
$my_date = date("Y-m-d H:i:s");
$order = uniqid();
$FullName= $_REQUEST['fullname'];
//Take in full Name and Split it into first and last name.
list($fname, $lname ) = explode( ' ', $customerName, 2 );
$address = $_REQUEST['address'];
$emailAddress = $_REQUEST['emailAddress'];
$phoneNo = $_REQUEST['phoneNo'];
Below is my Sticky Forum which is getting the Information from the Database and putting it into the Text Fields
// STICKY FORM TO ALLOW USER TO UPDATE INFORMATION
if (isset($_REQUEST['up']))
{
$query_sticky = mysqli_query($connection,'SELECT * FROM orders WHERE id = "' . $_GET['id'] . '"');
if(! $query_sticky )
{
die('Could not get data: ' . mysqli_error($connection)); // Could not find Order_id show Error
}//end die error
else
(isset($_REQUEST['update']));
{
while($row = mysqli_fetch_array($query_sticky, MYSQLI_ASSOC))
{
$row['id'];
echo '<form action="" method="post">'
Name:';
echo'<input name="customerName" id="cname" type="text" required value="'.$row['firstname']. " " .$row['lastname']. '" />';
echo' <br/>
<br/>
Address:
<textarea name="address" id = "caddress" type="text" rows="5" cols="30" required value="'.$row['address'].'" ></textarea>
<br/>
<br/>
Email Address:
<input name="emailAddress" type="email" required value="'.$row['email']. '" />
<br/>
<br/>
<br/>
Phone Number:
<input name="phoneNo" id="phoneNumber" type="text" required value="'.$row['phone']. '" />
<br/>
<br/>
<button type="submit" name="update" value="update" >update</button
<div id="Submit">
</form>
<form action="order.php" method="delete">
</form>';
}//close if
}
} // Close While
here is my Update Section
if (isset($_REQUEST['update']))
{
$updateDB = "UPDATE orders SET student ='$_POST[student]',
firstname='John', lastname='wallace',
email = '$_POST[emailAddress]', address = '$_POST[address]',
phone = '$_POST[phoneNo]'
WHERE
order_id ='$_GET[order_id]'";
mysqli_query($connection, $updateDB);
}//end update..
}//end PHP
?>
You were mixing up single and double quotes in your UPDATE query string. Try this instead:
$updateDB = "UPDATE test
SET email = '".#$_POST[$emailAddress]."',
address = '".#$_POST[$address]."',
phone = '".#$_POST[$phoneNo]."'
WHERE id = '".$_GET['id']."'";

Page redirecting back to login page after insert to db

My site has a simplistic login that when you go to an adminSLP page it redirects to the admin login page if the user isnt logged in. Problem is that when you are logged in to the page and try say inserting a record with the form i posted below it redirects you back to the login page. I cant see where I am going wrong.
ADMIN SLP
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['adminloggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: adminLogin.php");
exit;
}
ADMIN LOGIN
session_start();
if ($_GET['login']) {
// Only load the
code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['adminusername'] == '******'
&& $_POST['adminpassword'] == '*******') {
// Load code below if both username
// and password submitted are correct
$_SESSION['adminloggedin'] = 1;
// Set session variable
header("Location: adminSLP.php");
exit;
// Redirect to a protected page
} else echo '<style>#falseLogin{display: block!important;}</style>';
// Otherwise, echo the error message
}
LOGIN FORM
<form method="POST" action="adminLogin.php?login=true" id="adminlogin" style="padding:0">
<label for="adminusername">Username:</label>
<input type="text" name="adminusername" autocomplete="off"><br/>
<label for="adminpassword">Password:</label>
<input type="password" name="adminpassword" autocomplete="off" /><br/>
<input type="submit" value="Login">
</form>
FORM MADE FOR INSERTING RECORDS TO A DB
<form id="trainingForm" method="post" action="" style="display:block;">
<div>
<h2 id="title" style="color:#c89d64;font-size:36px;font-family: 'RokkittRegular'; margin:0 0 15px; padding:30px 0 30px 0;font-weight:normal;">Add New SLP</h2>
<label for="first_name">First Name</label><input id="first_name" name="first_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="last_name">Last Name</label><input id="last_name" name="last_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="title">Title</label><input id="title" name="title" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="user_phone">Phone*</label><input id="user_phone" name="user_phone" type="tel" value="(123) 456-7890" data-required="true" onFocus="if(this.value == '(123) 456-7890') this.value='';">
<label for="user_email">Email*</label><input id="user_email" name="user_email" type="email" value="name#something.com" data-required="true" data-validation="email" onFocus="if(this.value == 'name#something.com') this.value='';">
<label for="state_name">License Held In:</label><select name='state_name[]' id="state_name" multiple>
<?php
$result = mysqli_query($con,'SELECT * FROM license_state');
$count = 1;
while($row = mysqli_fetch_array($result))
{
echo '<option value=' . $row['state_name'] . '>' . $row['state_name'] . '</option>';
}
?>
</select>
<span><label for="isChecked">May we post your information on our site?:</label>
<input type="radio" name="isChecked" value="1" checked="checked"><p>Yes</p>
<input type="radio" name="isChecked" value="0"><p>No</p></span>
<label for="asha_number">Asha# (Will Not Be Published)*</label><input id="asha_number" name="asha_number" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_name">Practice Name*</label><input id="practice_name" name="practice_name" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_location">Practice Location*</label><input id="practice_location" name="practice_location" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<span><label for="telepracticeProvider">Are you a telepractice provider?:</label>
<input type="radio" name="telepracticeProvider" id="yes" value="Yes" ><p>Yes</p>
<input type="radio" name="telepracticeProvider" id="no" value="No" checked="checked"><p>No</p></span><br/>
<input type="hidden" id='user_id' name='user_id'/>
<br/><button name="submit" id="submit" type="submit">Submit</button>
</div>
</form>
insert to db
if(isset($_POST['submit']))
{// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","****","*****!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$insert = "INSERT INTO users ".
"(first_name,last_name, title, state_name, asha_number, practice_name, practice_location, user_phone, user_email, isChecked, telepracticeProvider) ".
"VALUES('$first_name','$last_name', '$title', '$implodeStates', $asha_number, '$practice_name', '$practice_location', '$user_phone', '$user_email', '$isChecked', '$telepracticeProvider')";
$insertData = mysqli_query( $con,$insert );
if(! $insertData )
{
die('Could not enter data: ' . mysql_error());
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";//RELOAD THE CURRENT PAGE</script><?php
} else if(isset($_POST['save'])){
// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","Speechvive","Slp2014!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_POST['user_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$update = ("UPDATE users SET first_name='$first_name',last_name='$last_name', title='$title', state_name='$implodeStates', asha_number='$asha_number', practice_name='$practice_name', practice_location='$practice_location', user_phone='$user_phone', user_email='$user_email', isChecked='$isChecked', telepracticeProvider='$telepracticeProvider' WHERE user_id = $user_id");
$updateData = mysqli_query( $con,$update );
if(! $updateData )
{
die('Could not enter data: ' . mysqli_error($con));
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";</script><?php
}
window.location = "http://www.speechvive.com/adminSLP.php";
why did you wrote this in insert to db part.. I think this is creating the problem

Check for duplicate entry in database before inserting

I’m trying to make a form that will check if the NRIC that is keyed exists in the database before it will insert the value into the database. However, I can’t seem to make it warn the user that there is already a duplicate entry. How do I go about doing it ?
Form:
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("first_name", "last_name", "nric", "address", "birthdate", "phone", "doctor");
validate_presences($required_fields);
$fields_with_max_lengths = array("phone" => 8);
validate_max_lengths($fields_with_max_lengths);
if( verify_nric($_POST['nric'])) {
$errors[] = 'This NRIC exists already.';
}
if( !isValid( 'phone', $_POST['phone'] ) ) {
$errors[] = 'Please enter a valid phone number';
}
if( !isValid( 'nric', $_POST['nric'] ) ) {
$errors[] = 'Please enter a valid nric number';
}
if (empty($errors)) {
// perform Create
$name = mysql_prep($_POST["name"]);
$age = (int) $_POST["age"];
$nric = mysql_prep($_POST["nric"]);
$birthdate = mysql_prep($_POST["birthdate"]);
$allergy = mysql_prep($_POST["medical_allergy"]);
$history = mysql_prep($_POST["medical_history"]);
$phone = (int)$_POST["phone"];
$address = mysql_prep($_POST["address"]);
$doctor = mysql_prep($_POST["doctor"]);
//escape content
// 2. Perform database query
$query = "INSERT INTO patients (";
$query .= " name, age, nric, birthdate, medical_allergies, medical_history,
phone, address, doctor_assigned";
$query .= ") VALUES (";
$query .= " '{$name}', {$age}, '{$nric}', '{$birthdate}',
'{$allergy}', '{$history}', {$phone}, '{$address}', '{$doctor}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Record Created.";
}else {
// Failure
$_SESSION["message"] = "Record creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<link rel="stylesheet" type="text/css" href="css/dashboard-icons.css" />
<link rel="stylesheet" type="text/css" href="css/dashboard-component.css" />
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Patient</h2>
<form action="create_patient.php" method="post">
<p>First Name:
<input type="text" name="first_name" value="" />
</p>
<p>Last Name:
<input type="text" name="last_name" value="" />
</p>
<p> NRIC/ Foreign ID/ Passport:
<input type="text" name="nric" value="" />
</p>
<p>Date Of Birth:<br />
<input type="text" name="birthdate" value="" />
</p>
<p>Contact Number:
<input type="text" name="phone" value="" />
</p>
<p>Address:
<textarea name="address" rows="1" cols="40" align="right"></textarea>
</p>
<p>Dentist Assigned:<br />
<input type="text" name="doctor" value="" />
</p>
<div id="limit">
<p>Medical Allergies:<br />
<textarea name="medical_allergy" rows="15" cols="40"></textarea>
</div>
<p>Medical History:<br />
<textarea name="medical_history" rows="15" cols="40"></textarea>
<input type="submit" name="submit" value="submit" />
</form>
<br />
Cancel
</div>
Validation Function:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "ORDER BY nric ASC";
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set);
if ($nric == $nric_set) {
return $nric_set;
}
}
function isValid( $what, $data ) {
switch( $what ) {
// validate a phone number
case 'phone':
$pattern = "/^[0-9-+()\s]+$/";
break;
case 'nric':
$pattern = "/^(A-Z)?[0-9]{7}[A-Z]$/i";
break;
default:
return false;
break;
}
return preg_match($pattern, $data) ? true : false;
}
confirm_query
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: ".
mysqli_connect_error() .
" (" . mysqli_connect_errno(). ")"
);
}
}
Not sure what confirm_query() does but you could change your function to:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "WHERE nric='".mysqli_real_escape_string($connection,$nric)."'"; //changed your query a little here
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set); // you haven't mentioned what this function does so I'm going to leave it that way.
$nric_found=false; //Added
if(mysqli_num_rows($nric_set)>0){ //
$nric_found=true; //These
} //
return $nric_found; //Lines
}
Now to explain where you went wrong:
Your select query returned all the nric but you weren't fetching the
values and checking against $nric. You need to use
mysqli_fetch_array() to get the values from the resultset
$nric_set
$nric == $nric_set is invalid because you are
comparing a resultset($nric_set) with a value $nric

Categories