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");
}
?>
Related
I have created a form with HTML/PHP/SQL where a user can either choose to submit their email into a database or else select a radio button to opt out of their email being submitted, alongside some other user data.
To achieve this, I have written an if/else statement, however my current code isn't working, and I can't quite work out the correct syntax that I should be using. If the user selects the radio-button, I would like "Email unavailable" to be inserted into the database, else the user-inputted email is inserted. All help appreciated!
Note, my code worked fine until I added the radio-button "no email" option.
HTML file:
<form id="newStaff" method="POST" action="staffportal.php" enctype="multipart/form-data">
<b><i class="fas fa-user-alt"></i> Full name:</b>
<input class="form-control" type="text" id="staffName" name="myStaffName" size="40" maxlength="50"/>
//THE RELEVANT CODE
<b><i class="fas fa-paper-plane"></i> Email:</b>
<div class="form-group row">
<div class="col-xs-4">
<input class="form-control" type="text" id="staffEmail" name="myStaffEmail" size="40"/>
<br>
<input class="form-check-input" type="radio" name="myStaffNoEmail" id="staffNoEmail" value="option1">
<label class="form-check-label" for="gridRadios1">
No available email
</label>
</div>
</div>
<hr>
<b>Job title(s):</b>
<input class="form-control" type="text" id="staffJob" name="myStaffJob" size="40" maxlength="60"/>
<b>Personal bio:</b>
<textarea class="form-control summernote" rows='6' cols='70' id="staffBio" name="myStaffBio" maxlength='1500'></textarea>
<b>Profile photo:</b>
<input type="file" class="custom-file-input" name="myStaffPhoto" id="staffPhoto">
<button name="newStaffBtn" id="newStaffButton" onclick="return confirm('Create new profile?');" type="submit" class="btn btn-primary">Create Profile></button>
</form>
PHP file:
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
$staffNoEmail = mysqli_real_escape_string($conn, $_POST["myStaffNoEmail"]);
//Staff email option
if (!empty($staffNoEmail)){
$staffEmail = "Email unavailable";
} else {
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
If radio input is checked, it will send value with post, if it is not checked it will not send any value and it will not exist in your $_POST array.In your case, you should be checking if it is set.
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
//Staff email option
if (isset($_POST["myStaffNoEmail"])){
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
} else {
$staffEmail = "Email unavailable";
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
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>
The main idea is to create a post along with multiple pictures that associate with the post but the entries for these posts are on a separate table.
I tried making it into one table to do both stuff, but I couldn't find a way to include more than one location for a file in on column.
HTML
<form action="includes/post.inc.php" method="POST" class="col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="title" name="title" type="text" class="validate" required>
<label for="title">Title</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="body" name="body" class="materialize-textarea" required></textarea>
<label for="body">Body</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="category" required>
<option value="" disabled selected>Choose a Category</option>
<option value="programming">Programming</option>
</select>
<label>Categories</label>
</div>
</div>
<div class="row">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="file[]" multiple>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
</div>
<button class="btn waves-effect waves-light right" type="submit" name="post-submit">Post</button>
</form>
PHP
function reArrayFiles($file_post){
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for($i = 0; $i<$file_count; $i++){
foreach($file_keys as $key){
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
global $idPost;
if (isset($_POST['post-submit'])) {
session_start();
$category = $_POST['category'];
$title = $_POST['title'];
$body = $_POST['body'];
$category = $_POST['category'];
$id = $_SESSION['userId'];
$uid = $_SESSION['userUid'];
$status;
if(empty($title) || empty($body)){
header("Location: ../index.php?error=emptyfields&title=".$title."&mail=".$body);
exit();
}else{
$sql = "INSERT INTO posts (titlePosts, contentPosts, catPosts, timePosts, statusPosts, uidUsers, idUsers) VALUES (?, ?, ?, NOW(), ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}else{
mysqli_stmt_bind_param($stmt, "ssssss", $title, $body, $category, $status, $uid, $id);
mysqli_stmt_execute($stmt);
}
}
$file_array = reArrayFiles($_FILES['file']);
$result = mysqli_query($conn, "SELECT idPosts FROM posts WHERE titlePosts={$title} AND bodyPosts={$body} AND idUsers={$id}");
while($row = mysqli_fetch_assoc($result)){
$idPost = $row['idPosts'];
}
for($i = 0; $i<count($file_array); $i++){
$fileName = $file_array[$i]['name'];
$fileTempName = $file_array[$i]['tmp_name'];
$fileSize = $file_array[$i]['size'];
$fileError = $file_array[$i]['error'];
$fileType = $file_array[$i]['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allow = array('jpg','jpeg','png','JPG','JPEG','PNG');
if(in_array($fileActualExt, $allow)){
if($fileError === 0){
if($fileSize < 100000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = '../uploads/'.$fileNameNew;
move_uploaded_file($fileTempName,$fileDestination);
mysqli_query($conn, "INSERT INTO post_files (locationFiles, idPosts) VALUES ({$fileNameNew},{$idPost})");
}else{
echo "<script>alert('Your file is too big!');</script>";
}
}else{
echo "<script>alert('There was an error uploading your file!');</script>";
}
}else{
echo "<script>alert('You cannot upload a file of this type!');</script>";
}
}
if(!isset($category)){
header("Location: ../index.php?post=success");
exit();
}else{
header("Location: ../index.php?cat={$category}&post=success");
exit();
}
}else{
header("Location: ../index.php");
exit();
}
post_files Table
|---------------------|------------------|------------------|
| idFiles | locationFiles | idPosts |
|---------------------|------------------|------------------|
| int | varchar(255) | int |
|---------------------|------------------|------------------|
idPosts is linked with the posts table
I expected the program to create a post along with the data from the fields, and for the files to be uploaded to htdocs and the file to be inserted into the data base. However, everything goes well except for entering data into the post_files Table.
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
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">