I am having trouble trying to get some values to insert into one of my tables.
It used to work fine but have recently changed my database and now does not insert.
I have stared at it for so long now i cannot see what is wrong, hopefully some one can see what is bound to be an obvious mistake.
The code is:
<?php
$date = $_POST['date'];
$plan = preg_replace('#[^A-za-z0-9 ?!.,]#i', '', $_POST['plan']);
if (isset($_POST['date'])) {
$sql = "SELECT * FROM maingroup WHERE groupName ='$g'";
$for_query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($for_query, MYSQLI_ASSOC)) {
$user = $row["owner"];
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan)
VALUES('$user','$g',now(),'$date','$plan')";
$query = mysqli_query($db_conx, $sessAdd);
$gid = mysqli_insert_id($db_conx);
}
header("location: groupPage.php?g=$g");
}
?>
<form name="addSess" id="addSess" method="post">
Date of Training: <input type="text" size="12" id="date" /></br></br>
Training:
<textarea name="plan" id="plan" rows="10" cols="80">
</textarea>
<script>
CKEDITOR.replace( 'plan' );
</script>
</br></br>
<input type="submit" value="Add Training" onclick="javascript:return validateMyForm();">
</form>
I have other pages that insert fine using more or less the same code just changing the table names and columns etc. The '$g' is established at the top of the page and gets the group info.
They all include a php script that connects to the database that works fine on the other pages also and elsewhere on the same page it calls data from another table so don't think its a connection problem. I have obviously gone blind to my error so am really hoping someone can see it.
Thank you to anyone that tries.
Try below code to insert
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan) VALUES('$user','$g',".now().",'$date','$plan')";
Just replace
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan)
VALUES('$user','$g',now(),'$date','$plan')";
By
$sessAdd = "INSERT INTO training (user, groupName, sessDate, plan)
VALUES('$user','$g','$date','$plan')";
Check your table whtr field date has default CURRENT_TIMESTAMP
Related
Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>
I created two tables:
First table, "users", consisting of 'user_id' (primary key), 'user_name', 'user_email' and 'user_pw'
Second table, "characters", consisting of of 'char_id' (primary key), 'uid', 'name', 'race' and age.
My intention is to let users create characters while the database assigns each created character to the correct user_id, so it's possible to find out who created what character.
(The login system is already working).
I started with the form, to fill in the character table:
<form method="post" action="includes/createcharacter.inc.php">
<input type="text" name="name">
<input type="text" name="race">
<input type="number" name="age">
<button type="submit" name="create">Erstellen</button>
</form>
Followed by the createcharacter.inc.php file, which is doing the php behind it:
<?php
if (isset($_POST['create'])) {
include_once 'dbh.inc.php';
$name = mysqli_real_escape_string($conn, $_POST['name']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$sql = "INSERT INTO characters (name, race, age) VALUES ('$name', '$race', '$age');";
mysqli_query($conn, $sql);
header("Location: ../createcharacter2.php?charactercreated");
exit();
}
It's no problem to insert the character data of a name, race and age now. But I can't figure out how to 'connect' the 'uid' row of my character-table with the user_id row of my user-table to assign every created character to a user_id.
I tried searching for an answer but I didn't know how to formulate it properly. I'm a beginner, so a detailed explanation would be appreciated.
Sweet jesus, sure took me smol brain all night to figure out how to insert it with the session. Here's my solution:
I simply added this input in my form:
if (isset($_SESSION['u_id'])) {
echo "
<form method='post' action='includes/createcharacter.inc.php'>
<input type='hidden' name='created_by' value='".$_SESSION['u_id']."'>
<input type='text' name='name'>
<input type='text' name='race'>
<input type='number' name='age'>
<button type='submit' name='create'>Erstellen</button>
</form>";
}
I also changed the name of the column 'uid' to 'created_by' like the - now deleted respond - suggested. Makes more sense to me. After that, the include-file looked like this:
<?php
if (isset($_POST['create'])) {
include_once 'dbh.inc.php';
$name = $_POST['name'];
$race = $_POST['race'];
$age = $_POST['age'];
$created_by = $_POST['created_by'];
$sql = "INSERT INTO characters (name, race, age, created_by) VALUES ('$name', '$race', '$age', '$created_by');";
mysqli_query($conn, $sql);
header("Location: ../createcharacter2.php?charactercreated");
exit();
}
Thanks for the advice regarding the risk of sql injection attacks. I'm programming on XAMPP right now, but I'll make sure to learn more about prepared and bound queries.
I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.
I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.
Ok, so after installing wamp server, I have gone to the phpMyAdmin page and created a database called db2. After that, I have created a table inside of that database called cnt2. It has 5 columns, ID, Name, Mark1, Mark2 and Mark3. So, I have one html php file that allows you to view the information in the database, and this works just fine. However, my second html php document is supposed to allow you to add new information into the database. I have followed 2 different tutorials on this as I have never done php or any html script before, but it just isn't working. I'll post both codes/scripts below.
http://gyazo.com/467f8e3a066992c0753eec2d5912bdba << Database page
http://gyazo.com/82a1c2107fb75c4c2941583449b4504a << Input page with error
Database code
<html>
<body>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("db2",$dbhandle)
or die("Could not selected db2");
echo "Coneted to db2<br>", "<br>";
$result = mysql_query("SELECT ID, Name, Mark1, Mark2, Mark3 FROM cnt2");
while($row = mysql_fetch_array($result)){
echo "<b>Name: </b>".$row{'Name'}." <b>ID: </b>".$row{'ID'}." <b>First Mark: </b>".$row{'Mark1'}." <b>Second Mark: </b>".$row{'Mark2'}." <b>Third Mark: </b>".$row{'Mark3'}."<br>";
}
mysql_close($dbhandle);
?>
</body>
</html>
Input code
<HTML>
<?php
if($submit){
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?
}
?>
</HTML>
Thanks for any help :)
You're not actually requesting your post headers to pull your vars in
<html>
<?php
if($submit){
//need to request post vars here
$id=mysql_real_escape_string($_POST['ID']);
$name=mysql_real_escape_string($_POST['Name']);
$markone=mysql_real_escape_string($_POST['Mark1']);
$marktwo=mysql_real_escape_string($_POST['Mark2']);
$markthree=mysql_real_escape_string($_POST['Mark3']);
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
mysql_query($sql) or die(mysql_error()."<br />".$sql);
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php // stop using short tags i've swapped it to a proper open
}
?>
</html>
Also if you're only just using don't use mysql_ functions look into mysqli or pdo especially prepared statements instead of directly injecting variables into queries as we have done above
The problem may be in this line:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
As You may notice (at the end), it should probably be like this:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
$result = mysql_query($sql);
As all other people mentioned, do not use mysql_* functions as they are DEPRECATED, instead of this stick with PDO or at least mysqli.
Also, the part
if($submit){
may never be satisfied unless You set the $submit variable somewhere before... Shouldn't it rather be
if (isset($_POST['submit'])) {
???
And, please, read about code formatting - Your code looks like crap... Best choice is to stick with PSR-0, PSR-1 and PSR-3 - use Google to read something about it...
create database android_api /** Creating Database **/
use android_api /** Selecting Database **/
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/