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.
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 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
I want to prevent if the user enters same email twice, which will create duplicate entry. Please help me to solve this small problem, I have searched stackoverflow for this problem but everyone has their own database with own method.
Thank you
<form action="create_subscriber.php" method="post">
<input placeholder="Name" name="inputName" type="name" required/>
<input name="inputEmail" placeholder="example#email.com" name="Submit" type="email" required/>
<input name="Submit" type="submit" value="Subscribe"/>
</form>
create_subscriber.php below
<?php
//include 'connection.php'
$dbhost = "localhost";
$dbuser = "sampleuser";
$dbpass = "samplepass";
$dbname = "sampledb";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
if(!$_POST['Submit']){
echo "Please enter a name & email";
//header('Location: index.php');
}else{
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES(NULL,'$name', '$email' ) ")
or die(mysql_error());
echo "User has been added";
header('Location: success.php');
}
?>
Since you are not doing any validation, you can use the Email as a unique field and do an REPLACE query. http://dev.mysql.com/doc/refman/5.0/en/replace.html
I would strongly advise you to write validation in the form of a query check against the database prior to attempting to do a secondary insert. It's even made easy by persistent connections being available so you don't have the overhead of few ticks it takes to do that validation query.
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES (NULL,'$name', '$email' )
WHERE NOT EXISTS (
SELECT email FROM subscriptions WHERE email='$email'
)")
Simply execute a preliminary query to check for email uniqueness
SELECT * FROM subscriptions WHERE `email` = ?
(I wrote the query in the form of a prepared statement
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You should use prepared statement to inject values into queries).
If you get any row then the email is not unique so redirect to the original form page, possibly displaying an error message.
If you don't get any record then you may proceed with the insert and then render a "mail registration succeeded" page.
Btw: you can't echo something and then set a header. As you start sending output header can't be set/changed.
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 **/
i keep getting the following error from this simple mysql statement and i cant see why. im sure its something obvious.
require_once("connect.php");
$query = mysql_query("SELECT * FROM accounts ORDER BY id DESC LIMIT 1");
$row = mysql_fetch_assoc($query);
$balanceold = $row['balance'];
$difference = $_POST['predec'].".".$_POST['dec'];
$category = $_POST['category'];
$notes = $_POST['notes'];
if(isset($_POST['in'])){
$balancenew = $balanceold + $difference;
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes) VALUES (".$balancenew.", ".$difference.", ".$category.", ".$notes.")");
if($query){
header("Location: budget.php");
}
else{
die(mysql_error());
}
}
gives error:
Unknown column 'payday' in 'field list'
here is my form code:
<form action=process.php method=post>
£
<input type=text name=predec size=7>
.
<input type=text name=dec size=4 value=00>
<br />
<select name=category>
<option value=payday>Payday</option>
</select>
<input type=text name=notes size=20>
<input type=submit name=in value=Deposit>
<input type=submit name=out value=Withdraw>
</form>
database table"accounts" contains the following fields:
id, int primary A_I
balancein, decimal 10,2
balanceout, decimal 10,2
current balance, decimal 10,2
category, varchar 50
notes, varchar 255
date, timestamp
...in that order
try this (enclose each variable inside query with single quota):
mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ('$balancenew', '$difference', '$category', '$notes')");
Its better to use mysqli or PDO to prevent from SQL injection attack, you could use mysql_real_escape_string() for now:
$balancenew = mysql_real_escape_string($balancenew);
and for other variables.
Thats because you have syntax error in your INSERT query. String and Date values are to passed into single quotes and not double quotes in sql. the . or the String concatenation character is also not required. So based on the data you provided it might be
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ($balancenew, $difference, '$category', '$notes')");
Basically what sql is telling you that you are referencing a column in your insert that is not defined in the database. Provide your table structure or ensure that the column name is exactly as you defined in the db. HTH.
You have missed single inverted commas enclosing $notes and $category I guess. Enclose them in ' and your problem should be solved.