PHP Can't enter data into database table - php

I am trying to enter the data that I get from the two variables stuname and book in the table's username and book columns !! I only want to enter data into those two columns since the id column is auto increment and the date is auto updated with time stamp!!! Each time I run my code I enter my data into the two text fields and when I press submit I get this message!!
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\assignment.php on line 35
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\assignment.php on line 36
Here is my Code:
<?php
$servername = "localhost";
$Username = "root";
$Password = "admin";
$Dbname = "nfc";
$conn = mysqli_connect($servername, $Username, $Password, $Dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connected successfully";
if(isset($_POST["stuname"])&&($_POST["book"]))
{
$stuname = $_POST["stuname"];
$book =$_POST["bookname"];
$sql = "INSERT INTO library (id, username, book, date)
VALUES ('', '$stuname', '$book','')";
mysqli_select_db($conn, 'nfc') or die(mysqli_error($con));
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
echo " to stuname ". $stuname;
echo " to book ". $book;
}
?>
<form id="form1" name="form1" method="post" action="#">
<p>
<label for="1">student name</label>
<input type="text" name="stuname" id="1" />
</p>
<p>
<label for="12">book name</label>
<input type="text" name="bookname" id="12" />
</p>
<input name="submit" type="submit" value="Submit" />
</form>

In the mysqli_query you should put the conn first and then the query itself
$retval = mysqli_query( $conn, $sql );

The first problem was solved by #Ghost in the comments.
Now on to the rest of the problems:
1. Your database design is faulty
This should have failed immediately because you are inserting an empty value for id. id should be a primary key and therefore should be unique. An auto-increment doesn't work if you insert an empty value.
2. Your insert statement is faulty
You should exclude an auto-increment column in the INSERT statement and should not use an empty value for date. If date is a timestamp, you should either use NULL if the time is supposed to be empty or use NOW() to use the current timestamp.
3. You shouldn't be using insert on this page according to your comments.
You should be using UPDATE or REPLACE instead of INSERT if you are trying to update the existing row but you should be using the primary key to signify which row you are replacing. Right now, it looks like you don't have a primary key, so refer to my 1st point.
4. Security concerns: Your query is subject to SQL injections.
You use user input ($_POST) directly in a query. Any malicious user can take advantage of this and extract, delete, or manipulate data in your database. You should be using prepared statements, or at the very least escape functions.

Related

Insert into SQL database user input from HTML form

I am trying to insert into column "UserId" in my sql database, using php, text that the user inputs in the HTML form.
Below is a basic example to help me figure out what I am doing wrong.
HTML
<html>
<form action="index1.php" method ="post" name="trial">
<input type="text" name="testName" id="testId">
<br>
<input type="submit" value="Submit">
</form>
</html>
PHP
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "wp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Some notes:
I can connect to database and insert in the correct columns checkbox and radio values from the form
I cannot find a way to insert in the database the user text input from the form (UserProfile is the table and UserId the column).
Would using a javascript variable, like below one, help?
var testVar = document.getElementById("testId").value;
I know I am opening myself to hacking using the above code, I would like to improve it later on but I think I need to first figure out the basics (ie: how to get the user text input added to the database)
Than you in advance for any help!
you are storing the value in $UserId, not in $testName:
Change your SQL Query to
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
I think this will help.
BTW: Think about SQL-Injection! Look here: How can I prevent SQL injection in PHP?
Look here
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
Change $testName to $UserId in sql statement because it's the name of your new variable in php:
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
But I advice you to:
1- use PDO for any sql handling in php
2- use mysqli_real_escape_string to protect your code from threats.
make it like:
$UserId = mysqli_real_escape_string($con, $_POST['testName']);

PHP add unique Id to SQL

I'm working on a small project for my English teacher, and it's my first time doing anything with databases. I have a table called Books, with four columns: Id, Title, Link, and Rating. The idea is that a user could submit the title of a book they recently read, a link to it on goodreads, and a rating out of 5 stars. (I don't have any input validating yet, but I'm going to add that after I finish up with my current problem.)
The problem happens in the Id column. I'm trying, with PHP and SQL, to grab the largest Id in the entire table, and then set the Id of the newly added book (row) to be one more than the old largest.
Here's my HTML:
<form action="bookSubmit.php" method="post">
Book Title: <input type="text" name="title"><br>
Goodreads Link: <input type="text" name="link"><br>
Rating (1 to 5): <input type="number" name="rating" min="1" max="5"><br>
<input type="submit" value="submit">
</form>
and bookSubmit.php:
<?php
$servername = "localhost";
$username = "[My username]";
$password = "[My password]";
$dbname = "PullJosh_books";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$newId = $conn->query("SELECT MAX(Id) FROM Books"); // Replacing this line with $newId = and then manually typing in the current highest Id works (meaning everything else is all set).
$newId++;
$sql = "INSERT INTO Books (Id, Title, Link, Rating)
VALUES ('". $newId ."', '" . $_POST['title'] . "', '" . $_POST['link'] . "', '" . $_POST['rating'] . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When I run SELECT MAX(Id) FROM Books in the phpmyadmin sql tab, I get 2, which is correct.
If you happen to notice any security issues (besides not validating the input), please let me know about that as well.
You need not to first find the largest number in the table and then add one number to it and then submit. In your data table in mysql turn id into primary key and make it auto increment true that will always insert a unique and increased id.
syntax for the same
ALTER TABLE tbl_name ADD id INT PRIMARY KEY AUTO_INCREMENT;

Using PHP to add to a database created in WAMP server?

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 **/

Connecting html form to php page according to primary key

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.

PHP Cannot Add Or Update Child Field - Foreign Key Error

I am getting an error when trying to insert some values into a MySQL Database - My page currently reads the value 'EventID' which is passed through the URL and allows me to Add Results based on that EventID. I currently have a Drop down box which is populated by the Members within the members table.
I get this horrid error:
Cannot add or update a child row: a foreign key constraint fails (clubresults.results, CONSTRAINT ResultEvent FOREIGN KEY (EventID) REFERENCES events (EventID) ON DELETE CASCADE)
I am not able to change the table structure so any help would be great appreciated.
Note - I'm currently having it echo the SQL to find the error as to why it won't insert.
<?php
error_reporting (E_ALL ^ E_NOTICE);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("clubresults", $con);
// Get id from URL
$id = mysql_real_escape_string($_GET['EventID']);
// If id is number
if ($id > 0)
{
// Get record from database
$sql = "
SELECT EventID
FROM results
WHERE EventID = " . $id;
$result = mysql_query($sql);
}
if (isset($_POST['submit'])) {
$sql="INSERT INTO results (MemberID, Score, Place)
VALUES
('".$_POST['student']."', '".$_POST['Score']."', '".$_POST['Place']."')";
$add_event = mysql_query($sql) or die(mysql_error());;
echo $add_event;
}
HTML Form -
$_SERVER['PHP_SELF']?>" method="post">
<table border="0"><p>
<tr><td colspan=2></td></tr>
<tr><td>Member Name: </td><td>
<?php
$query="SELECT * FROM members";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value='$nt[MemberID]'>$nt[Firstname] $nt[Surname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<tr><td>Score:</td><td>
<input type="text" name="Score" maxlength="10">
<tr><td>Place:</td><td>
<input type="text" name="Place" maxlength="10">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Add Result"> </th></tr> </table>
</form>
You have to insert the EventID into your results record:
$sql="INSERT INTO results (MemberID, Score, Place, EventID) VALUES (?, ?, ?, ?)";
Note I have used ? placeholders in place of your $_POST variables (which left you vulnerable to SQL injection).
You should use instead prepared statements into which you pass your variables as parameters that do not get evaluated for SQL, but they are not available in the ancient MySQL extension that you're using (which the community has begun deprecating anyway, so you really should stop writing new code with it); use instead either the improved MySQLi extension or the PDO abstraction layer.

Categories