Inserting steam user info in db - php

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

Related

How to pass an id of current item to request table

I have an application where a user can send request edit to the admin, now the problem is how to store the id of the requested asset from user_asset table to the request table so I can display it to the admin's page with full details of the asset
when the user clicks on the request edit he gets a form with editable fields filled with current information but how can I store this asset's id so I can fetch it to the admin's table with information from both tables (user_assets, requests)
I have user_asset table
asset_id
asset_category
code
title
userid
and requests table
id
reason
assetid
user_id
this is what I have done so far
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
?>
and this is my form
<form method="post" action="req_ade.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
these are the errors I'm getting
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Incorrect integer value: '' for column 'assetid' at row 1' in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
( ! ) mysqli_sql_exception: Incorrect integer value: '' for column 'assetid' at row 1 in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
There is no "id" in your $_GET array. So your $asset_id variable will be empty and a empty string is not a valid int number. You should add (int) in your query:
mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". (int)$asset_id ."','" .$_SESSION['user_id'] . "')")
Or better check the the $_GET array before you use it. Like this:
If(isset($_GET['id']))
{
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
}
else
{
...
}
Thank you for all your suggestions.
After trying a lot of suggestions and manipulating with the code I have found a solution for it.
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_POST['asset_id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests1`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
and this is the form I have posted the asset_id in a hidden type
<form method="post" action="req_ade1.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="hidden" value="<?php echo $project['asset_id'];?>" name="asset_id" />
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>

Foreign key(newbie)

I want to insert the foreign key of my customer_id in my feedback table. How should I do it?
customer table:
customer_id
coach_id
customer_name
feedback table:
feedback_id
feedback1
feedback2
customer_id
I want to do it where after user login, user insert information of the feedback it will automatically register the customer id.
This is my code after I login and want to register feedback:
<?php
session_name ('YourVisitID');
session_start();
$page_title = 'Feedback';
include('./header4.html');
//remember to delete.
echo "{$_SESSION['customer_name']}";
?>
<section id="main" class="wrapper">
<div class="container">
<form action = "feedback.php" method="post">
<div class="row uniform 50%">
<div class="6u 12u$(xsmall)">
<input type="text" name="weight" placeholder="Weight"
required autofocus/>
</div>
<div class="6u$ 12u$(xsmall)">
<input type="text" name="height" placeholder="Height"
required autofocus/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="water" placeholder="Water Level%"
required autofocus/>
</div>
<div class="6u$ 12u$(xsmall)">
<input type="text" name="body_fat" placeholder="Body Fat%"
required autofocus/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="calorie" placeholder="Calorie"
required autofocus/>
</div>
<div class="6u$ 12u$(xsmall)">
<input type="text" name="visceral" placeholder="Visceral Fat Level%"
required autofocus/>
</div>
<p><input type="submit" name="submit" value="Register" /></p>
<input type="hidden" name="submitted" value="TRUE" />
</div>
</form>
</div>
</section>
<?php
if(isset($_POST['submitted'])) {
require_once ('mysql_connect3.php');
function escape_data ($data){
global $dbc;
if (ini_get('magic_quotes_gpc')){
$data = stripslashes($data);
}
return mysql_real_escape_string(trim($data), $dbc);
}
$error = array();
$weight = escape_data($_POST['weight']);
$height = escape_data($_POST['height']);
$water = escape_data($_POST['water']);
$calorie = escape_data($_POST['calorie']);
$visceral = escape_data($_POST['visceral']);
$fat = escape_data($_POST['body_fat']);
mysqli_close($con);
header("location: add_user.php?remarks=success");
if (empty ($errors)) {
$query ="SELECT * FROM feedback WHERE weight ='$weight'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
$query = "INSERT INTO feedback (weight, height, body_fat, water, calorie, visceral, feedback_date) VALUES
('$weight', '$height', '$water', '$calorie', '$visceral','$fat', NOW() )";
$result = #mysql_query ($query);
if ($result) {
echo '<script>
alert("Your feedback has been save");
</script>';
include ('./footer.html');
exit();
}else{
echo '<script>
alert("<h1 id="mainhead">System Error</h1>
<p class="error">You could not give feedback due to a system error.
We apologize for any inconvenience.</p>");
</script>';
echo '<p>'. mysql_error() . '<br /><br />Query: ' . $query . '</p>';
include ('./footer.html');
exit();
}
}
}else{
echo '<script>
alert("<h1 id="mainhead">Error!</h1>
<p class="error">Please try again.</p>");
</script>';
}
mysql_close();
}
?>
<?php
include ('./footer.html');
?>
I think you should define in sql table schema.
After you define foreign key customer_id in feedback table
You can use PHP to select data from that table
When a customer logs in, just store its customer_id in the session, just as you store its customer_name at the moment. When the customer submits the feedback form, you simply provide the customer_id from the session.
$query = "INSERT INTO feedback (weight, height, body_fat, water, calorie, visceral, feedback_date, customer_id) VALUES
('$weight', '$height', '$water', '$calorie', '$visceral','$fat', NOW(), ".$_SESSION ['customer_id']. ")";
$result = #mysql_query ($query);
Couple of notes:
Do not use mysql_*() functions any longer, they have been deprecated years ago and has been removed as of php7. Use mysqli or pdo instead.
Use prepared statements with parameter binding to prevent sql injection attacks.
Do not mix various mysql apis.

Insert data into separate tables related by foreign keys

I have a database with two tables:
posts: id(primary key, autoincrement), title_bg, title_en, body_bg, body_en, status, created, updated
postimage: id(primary key, auto increment), post_id, name
When I'm not using a foreign key, the form with multiple elements is working fine. It fills all the details for the post into the posts table and the multiple images are uploading into the postimage table, but they're not related, so the post_id field shows 0 value.
When I set the foreign key on phpMyAdmin with this query:
ALTER TABLE `postimage` ADD FOREIGN KEY ( `post_id` ) REFERENCES `database_name`.`posts` ( `id` ) ON DELETE RESTRICT ON UPDATE RESTRICT ;
and when I create a new post, all the values are saved into the posts table, except the images into the second table. The postimage table is empty.
Here's my code:
<?php
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(name) ";
$query .= "VALUES('$name')";
$upload_images = mysqli_query($connection, $query);
}
}
$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title_bg">Post title BG</label>
<input type="text" name="title_bg">
</div>
<div class="form-item">
<label for="title_en">Post title EN</label>
<input type="text" name="title_en">
</div>
<div class="form-item">
<label for="body_bg">Post body BG</label>
<textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="body_en">Post body EN</label>
<textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="published">published</option>
<option value="draft">draft</option>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Submit">
</div>
</form>
I've also created a two new tables as a test:
teachers: id, name, content_area, room
students: id, name, homeroom_teacher
When I set the foreign key on students field homeroom_teacher and insert the data manually from phpMyAdmin, they become related and the id on students table becomes clickable and it shows the relation with the teacher. So manually it's working great and the problem is in the PHP code.
What query do I need to change, so to make the connection with post id from the posts table and post_id from the postimage table?
I know that I'm missing the id from the $_FILES query, but I don't know how to get it, because it's already automatic auto increment field.
Thanks.
<?php
if(isset($_POST['status'])) {
$status = $_POST['status'];
}
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
$connection = new mysqli("localhost", "USER_XY", "PASSWD","DB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die ("<h1>can't use Database !</h1>");
exit();
}
/* change character set to utf8 */
if (!$connection->set_charset("utf8")) {
printf("Error while loading 'character set utf8' : %s\n", $connection->error);
die();
}
/**
* First save the Post
**/
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$result=$connection->query($query);
// verify results
if(!$result) {
$message = "ERROR SAVING POST : ".$connection->error . "\n";
$connection->close();
echo ($message);
return false;
}
/**
* get the last inster id of the Post
**/
$post_id = $connection->insert_id;
echo "Post id=".$post_id ."<br>\n";
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, './uploads/' . $name);
/**
* now insert the image with the post_id
**/
$query = "INSERT INTO `postimage` (`id`, `post_id`, `name`) ";
$query .= "VALUES (NULL, '".$post_id."', '".$name."');";
$result=$connection->query($query);
// verify results
if(!$result) {
$message = "ERROR INSERT IMAGE : ".$connection->error . "\n";
$connection->close();
echo ($message);
return false;
}
}
}
header("Location: upload_posts.php");
}
?>
<form action="upload_posts.php" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title_bg">Post title BG</label>
<input type="text" name="title_bg">
</div>
<div class="form-item">
<label for="title_en">Post title EN</label>
<input type="text" name="title_en">
</div>
<div class="form-item">
<label for="body_bg">Post body BG</label>
<textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="body_en">Post body EN</label>
<textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="published">published</option>
<option value="draft">draft</option>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Submit">
</div>
</form>
autoincrement id's can be obtained with $mysqli->insert_id;
see for furter details : https://php.net/manual/mysqli.insert-id.php
:-)
I think it's problem because you add data first in postimage and after that add data in post so post_id is not found in postimage try to change postion of query like: `$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(name) ";
$query .= "VALUES('$name')";
$upload_images = mysqli_query($connection, $query);
}
}
use this: $last_id = mysqli_insert_id($conn); to get the last inserted id.
<?php
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
$last_id = mysqli_insert_id($connection);
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(post_id, name) ";
$query .= "VALUES('$last_id', '$name')";
$upload_images = mysqli_query($connection, $query);
}
}
header("Location: posts.php");
}
?>

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">

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

Categories