Input information to database, display it with PHP - php

I have a form where I enter text, then it goes to the database and after I want it to be immediately displayed on the same page. I enter the info and submit it, page reloads and nothing appears in database or page. Any ideas maybe?
Saving part:
if(isset($_POST['ok'])){
$Vardas = $_POST['vardas'];
$Epastas = $_POST['epastas'];
$Kam = $_POST['kam'];
$Zinute = $_POST['zinute'];
$Date = date('Y-m-d H:i:s');
/*$IP = $_SERVER[REMOTE_ADDR];*/
}
//else {die ("Neuzpildyta forma");}
$sql = "INSERT INTO table1 (vardas, epastas, kam, data, zinute)
VALUES ('$Vardas', '$Epastas','$Kam', '$Date', '$Zinute')";
//if (mysqli_query($dbc, $sql)) echo "Įrašyta";
//else die ("Klaida įrašant:" .mysqli_error($dbc));
Form:
<form method='post' action="">
<div class="form-group col-lg-4">
<label for="vardas" class="control-label">Siuntėjo vardas:</label>
<input name='vardas' type='text' class="form-control input-sm">
</div>
<div class="form-group col-lg-4">
<label for="epastas" class="control-label">Siuntėjo e-paštas:</label>
<input name='epastas' id="epastas" type='email' class="form-control input-sm">
</div>
<div class="form-group col-lg-4">
<label for="kam" class="control-label">Kam skirta:</label>
<input name='kam' type='text' class="form-control input-sm">
</div>
<div class="form-group col-lg-12">
<label for="zinute" class="control-label">Žinutė:</label>
<textarea name='zinute' class="form-control input-sm"></textarea>
</div>
<div class="form-group col-lg-2">
<input type='submit' name='ok' value='siųsti' class="btnbtn-default">
</div>
</form>

It looks like you're missing your $mysqli connection. Your code is also very susceptible to mysql injection so here is my recommendation.
$mysqli = new mysqli("localhost", "username", "password", "database_name");
if(isset($_POST['ok'])){
$Vardas = $mysqli->real_escape_string($_POST['vardas']);
$Epastas = $mysqli->real_escape_string($_POST['epastas']);
$Kam = $mysqli->real_escape_string($_POST['kam']);
$Zinute = $mysqli->real_escape_string($_POST['zinute']);
$Date = date('Y-m-d H:i:s');
$my_insert_query = "INSERT INTO table1 (vardas, epastas, kam, data, zinute)
VALUES ('$Vardas', '$Epastas','$Kam', '$Date', '$Zinute')";
$insert = $mysqli->query($my_insert_query);
if($insert){
echo "Success!";
}else{
echo "error" . $mysqli->error;
}
}
The code above should work and prevent any sql injection.

Related

Inserting steam user info in db

Im trying to insert the steamid , steam real name . steam name into my db when the user login in my website
mycode :
<?php
if (isset($_GET['login'])){
$steamids= $steamprofile['steam_steamid'];
$name = $steamprofile['personaname'];
$real = $steamprofile['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
$button = "<a href='?login'><img src='http".(isset($_SERVER['HTTPS']) ? "s" : "")."://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_".$button[$buttonstyle].".png'></a>";
When the user log in i dont get anything in the db .
i tried to store the user info using sessions and it works but alway duplicate the value
the code is a little bit messy Because im still learning
Any Idea?
<?php
$db = array("DB_HOST"=>"localhost","DB_USER"=>"root","DB_PASS"=>"mysql","DB_NAME"=>"databasename",);
foreach ($db as $key => $value)
{
define($key , $value);
}
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (!$connection)
{
die ('<h1>connecting failed</h1>');
}
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection , $query);
if ($insert_query) {
echo "User added";
}else{
die("we have error " . mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit" name="login"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
check it we have create data base and check my code it work my table user have
steamid (varchar 255)
steamname (varchar 255)
steamreal (varchar 255)
user_logindate (Date)
i don't saw your HTML Form but i added and i think its work check this
<?php
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
you can add your src in image tag just copy and paste it in image Tag

How would one skip empty field values when submitting a form using PHP?

I have a form that echoes values for a specific user from a MySQL database using PHP. I am trying to figure out how to allow the user to submit the form to update their user information but have the form skip any field they have no filled out.
Current update statement
if (!isset($_POST['btnLogin'])) {
$db = DB();
$stmt = "UPDATE users SET fName = :fName,
lName = :lName,
emailAddress = :emailAddress
WHERE user_id = $user->user_id";
$query = $db->prepare($stmt);
$query->bindParam(':fName', $_POST['fName'], PDO::PARAM_STR);
$query->bindParam(':lName', $_POST['lName'], PDO::PARAM_STR);
$query->bindParam(':emailAddress', $_POST['emailAddress'], PDO::PARAM_STR);
$query->execute();
};
Form echoing user information
<form class="form-horizontal" action="profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" type="text" name="fName" placeholder="<?php echo $user->fName ?>"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" type="text" name="lName" placeholder="<?php echo $user->lName ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="email" name="emailAddress" placeholder="<?php echo $user->emailAddress?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8" style="margin-top: 7px;">
<?php echo $user->username ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" name="btnUpdate" value="Save Changes" type="button">
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
Currently this doesnt appear to update the database at all. If I leave the form completely blank and submit it, the values that existed in the database are now empty. i.e., just blank columns.
I have been looking at other examples on how to do this but I cannot seem to figure this out. Any help would be appreciated.
Just to be sure I am in fact updating the correct user, I made sure that my $user->user_id statement is in fact returning the correct user_id from the database for the update.
UPDATE
Currently this is how I have the update statement / code
if(!empty(['btnUpdate'])) {
$stmt = "UPDATE users SET fName = IF(:fName = '', fName, :fName),
lName = IF(:lName = '', lName, :lName),
emailAddress = IF(:emailAddress = '', emailAddress, :emailAddress)
WHERE user_id = $user->user_id";
$db = DB();
$query = $db->prepare($stmt);
$query->bindParam("fName", $fName, PDO::PARAM_STR);
$query->bindParam("lName", $lName, PDO::PARAM_STR);
$query->bindParam("emailAddress", $emailAddress, PDO::PARAM_STR);
$query->execute();
}
Using <?php var_dump($_POST) ?> returns 0 after submitting the form and I still end up with empty database columns
This isn't ignoring empty fields, but a more user friendly solution would be to stick the database values into each input's value attribute. That way, you don't have to skip the fields if they're blank, and a user won't get confused when editing their data. If you don't want them to be able to edit the value, just include the readonly attribute.
If you don't want to do this, than you could either create a dynamic query or use an if statement to decide which value to use, the form's or the database's.
You can make the query check whether the value is empty, and reuse the existing value.
$stmt = "UPDATE users SET fName = IF(:fName = '', fName, :fName),
lName = IF(:lName = '', lName, :lName),
emailAddress = IF(:emailAddress = '', emailAddress, :emailAddress)
WHERE user_id = $user->user_id";
You could also build the query and parameters dynamically.
$sets = array();
$params = array();
foreach (array('fName', 'lName', 'emailAddress') as $field) {
if (!empty($_POST[$field])) {
$sets[] = "$field = :$field";
$params[":$field"] = $_POST['field'];
}
}
if (!empty($sets)) {
$sets_string = implode(', ', $sets)
$stmt = "UPDATE users SET $sets_string WHERE user_id = :id";
$params[":id"] = $user->user_id;
$query = $db->prepare($stmt);
$query->execute($params);
}

how update value input form class result

I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)

Insert formfields to SQL - Error

Hi so I have a form with 10 fields and I am trying to insert them on an SQL databse through posting them on a PHP page. Connection starts fine, but it returns the error below:
Error: INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES (, , , , , , , , , )
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , , , , , , )' at line 1
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$teacher = $_POST['teacher'];
$description = $_POST['description'];
$class = $_POST['class'];
$dayone = $_POST['dayone'];
$daytwo = $_POST['daytwo'];
$daythree = $_POST['daythree'];
$std1 = $_POST['std1'];
$std2 = $_POST['std2'];
$std3 = $_POST['std3'];
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ($name, $teacher, $description, $class, $dayone, $daytwo, $daythree, $std1, $std2, $std3)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
I should also mention that the database table has one more field called ID type int(11) which is AUTO_INCREMENT and I expect it to be automatically filled everytime a new row is inserted. Am I wrong?
EDIT: Added HTML code since it has been asked
<form name="registration_form" method="post" class="clearfix" action="create.php">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" id="name" placeholder="Course Name">
</div>
<div class="form-group">
<label for="teacher">Teacher</label>
<input type="text" class="form-control" id="teacher" placeholder="Teacher's Name">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" placeholder="Description"></textarea>
</div>
<div class="form-group">
<label for="class">Class</label>
<input type="text" class="form-control" id="class" placeholder="Class Name">
</div>
<div class="form-group">
<label for="dayone">Day one</label>
<input type="text" class="form-control" id="dayone" placeholder="Day One">
</div>
<div class="form-group">
<label for="daytwo">Day two</label>
<input type="text" class="form-control" id="daytwo" placeholder="Day Two">
</div>
<div class="form-group">
<label for="daythree">Day three</label>
<input type="text" class="form-control" id="daythree" placeholder="Day Three">
</div>
<div class="form-group">
<label for="std1">std1</label>
<input type="text" class="form-control" id="std1" placeholder="std1">
</div>
<div class="form-group">
<label for="std2">std2</label>
<input type="text" class="form-control" id="std2" placeholder="std2">
</div>
<div class="form-group">
<label for="std1">std3</label>
<input type="text" class="form-control" id="std3" placeholder="std3">
</div>
<div class="checkbox">
<label>
<input type="checkbox">I Understand Terms & Conditions
</label>
</div>
<button type="submit" class="btn pull-right">Create Course</button>
</form>
This should help you identify if the issue is POST variables not being received.
Also a little bit more security.
// create an array of all possible input values
$input_array = array('name', 'teacher', 'description', 'class', 'dayone', 'daytwo', 'daythree', 'std1', 'std2', 'std3');
// create an input array to put any received data into for input to the database
$input_array = array();
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// loop through the possible input values to check that a post variable has been received for each.. if received escape the data ready for input to the database
foreach($input_array as $key => $value)
{
if(!isset($_POST[$value])) {
die("no {$value} post variables received");
}
$input_array[$value] = mysqli_real_escape_string($conn, $_POST[$value]);
}
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('{$input_array['name']}', '{$input_array['teacher']}', '{$input_array['description']}', '{$input_array['class']}', '{$input_array['dayone']}', '{$input_array['daytwo']}', '{$input_array['daythree']}', '{$input_array['std1']}', '{$input_array['std2']}', '{$input_array['std3']}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Try:
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('".$name."', '".$teacher."', '".$description."', '".$class."', '".$dayone."', '".$daytwo."', '".$daythree."', '".$std1."', '".$std2."', '".$std3."')";
Also, use:
$name = $conn->real_escape_string($_POST['name']);
//etc
Also add name to your form fields:
<input name="class" type="text" class="form-control" id="class" placeholder="Class Name">

Failed to upload a file in PHP

I try to upload an image, but it is not working. Other variables I have set are inserted into database, but image file is not... I was trying to check submit with isset, but it is not working. Where is my error?
Thanks for your help.
PHP file:
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno) {
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)) {
$i1 = strrpos($upload,".");
if (!$i1) {
return "";
}
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = copy($_FILES['upload']['tmp_name'], $newname1);
} else {
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This is my HTML file:
<form class="cmxform form-horizontal tasi-form" name="form2" id="form2" method="post" action="">
<div class="form-group ">
<label for="icode" class="control-label col-lg-2">Item Code</label>
<div class="col-lg-10">
<input class=" form-control" id="icode" name="icode" type="text" />
</div>
</div>
<div class="form-group ">
<label for="iname" class="control-label col-lg-2">Item Name</label>
<div class="col-lg-10">
<input class=" form-control" id="iname" name="iname" type="text" />
</div>
</div>
<div class="form-group ">
<label for="brandname" class="control-label col-lg-2">Brand Name</label>
<div class="col-lg-10">
<input class=" form-control" id="brandname" name="brandname" type="text" />
</div>
</div>
<fieldset style="width:48%; float:left;"> <!-- to make two field float next to one another, adjust values accordingly -->
<label>Doc 2</label>
<input style="margin: 0 10px;" type="file" name="upload" size="50">
</fieldset>
Add 'enctype="multipart/form-data"' to your form tag attributes, you can read more about file uploading here.
Also consider checking the values of the post, because your current method can get you sql injections
add form attribute enctype="multipart/form-data"
You have not proper syntax used and also use 'enctype="multipart/form-data"'.
I have implemented your code
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno){
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)){
$i1 = strrpos($upload,".");
if (!$i1) { return ""; }
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = $_FILES['upload']['tmp_name'], $newname1;
}else{
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>

Categories