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

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

Related

Sql Limitation on Database Name [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I was trying to make a sql database and i have faced some issues regarding INSERT INTO TABLE.
I have noticed that sql is not allowing me to insert data in a table if the name of Database is u759286173 i am able to insert data into table using any other name but this particular (u759286173) database name is not allowing me to insert data in table
I have tried various database names which works
759286173
759286173_quebec
759286173_grvnaz
u_grvnaz
Can someone please explain me that why data is not inserting in table when i allow the database name to be u759286173
My Database name : u759286173
My Table name : mydb
Please reply if u face the same issue or have a solution.
Any help is appreciated.
My Code
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "u759286173";
$dbHost = " localhost";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
other code
<?php
session_start();
include 'dbh.inc.php';
if (isset($_POST) & !empty($_POST)) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO mydb (first, last, email, message)
VALUES ('$first', '$last', '$email', '$message');";
mysqli_query($conn, $sql);
header("location: ../signup.php?send=success");
} else {
header('location: ../failed.php');
exit();
}
?>
Form Code
<!DOCTYPE>
<html>
<body>
<form class="registerform" action="includes/contact.inc.php" method="POST">
<input type="text" placeholder="first" name="first" required/>
<input type="text" placeholder="last" name="last" required/>
<input type="email" placeholder="E-mail ID" name="email"/>
<input type="text" placeholder="message" name="message" required/>
<button name="submit" type="submit">Create</button>
</form>
</body>
</html>
=Database u759286173
CREATE TABLE IF NOT EXISTS `mydb` (
`id` int(11) NOT NULL,
`first` varchar(32) NOT NULL,
`last` varchar(32) NOT NULL,
`email` varchar(50) NOT NULL,
`message` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The INSERT statement does not provide a value for the id column.
The id column is defined to be NOT NULL and does not have AUTO_INCREMENT property. (And we assume there isn't a BEFORE INSERT trigger that assigns a value to NEW.id
Given the table definition, we expect that when the INSERT statement is executed, MySQL will issue
Error Code: 1364
Field 'id' doesn't have a default value
(This could be a Warning rather than Error with some settings of sql_mode.)
Most important is that we check for MySQL error condition; this will provide the information we need in order to determine what the problem is.
At the top of the script, enable PHP and mysqli error reporting:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
That will get use the information we need when a MySQL error occurs.

cant get code to insert to table

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

PHP Can't enter data into database table

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.

PHP MYSQL Prevent user or email inserted twice

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.

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.

Categories