Connecting to a database using php script - php

I have created a form in HTML and the action is set to a php script. I'm pretty new to php and was wondering if someone could help me out with it? I need to write a script to add the info from the form to a database. I need to create the database and the table as well. I did a lot of reading on the net and I'm still unable to do it. This is the script I have. Please tell me what mistakes I have made. Thank you for all the help.
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
$sql="CREATE DATABASE user";
if (mysql_query($con,$sql)) {
echo "Database user created successfully";
}
$sql="CREATE TABLE Persons(PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID),firstName CHAR(30),lastName CHAR(30),age INT, dateofbirth DATE, email CHAR(30)";
if (mysql_query($con,$sql)) {
echo "connected to database";
}
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
if (mysql_query($con,$sql)) {
echo "added to database";
}
mysql_close($con);
?>
I tried all the suggested answers and still not able to do it. Can someone please provide the code to do that? I need to obtain data from a form and insert it into a database using php!

Hi Try This Code,
$con=mysql_connect("example.com","peter","abc123");
$sql="CREATE DATABASE user";
if (mysql_query($sql))
{
echo "Database user created successfully";
}

1.- Don't use mysql_ functions because are deprecated, use mysqli_ functions or PDO instead.
2.- You have several error i guess, first of all you select a database my_db on the connection script, but you are created another database in the next line... it's very strange this behaviour. If this script executes every time then you should change your code (you can't create a database and a table every time.
In the insert string you have an error with the post code, try this:
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}','{$_POST['dateofbirth']}','{$_POST['email']}')";

Your CREATE TABLE query will fail because of syntax error. You have to check queries results especially when next query depends on previous (and you're doing operations like creating databases/tables).
Next thing to change is mysql_*. This functions are deprecated and instead you should use PDO or mysqli_* (they are not hard to learn, just try).
And one more important change have to be done in your script. You're getting user input and adding it to query. Don't do that! You have to always assume that user is trying to hack you, so all inputed data have to be checked and filtered. Also it's good to use prepared statements with such data.

if (mysql_query($con,$sql)){
echo "Database user created successfully";
} else {
echo 'Error creating database - ' . mysql_error();
}
Same thing for all your sql statements to see where you went wrong

Change your code (mysql_query($sql)) instead of (mysql_query($con,$sql))

Related

MySQL Insert Into PHP Not Working

I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.

How to use same query to insert data

I am new at programming.
I am trying to create a simple guestbok.
i have one index page where you can register a firstname, lastname and email.
And if you click on one name you redirect to a new page with id.
How can i now insert text to this ID with the same codeblock using the ID.
My code looks like this.
<?php
require('dbconfig.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
//Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert to database
$sql = "INSERT INTO user (firstname, lastname, email)
VALUE ('".$_POST["first_name"]."','".$_POST["last_name"]."','".$_POST["email"]."')";
$sql = "INSERT INTO user (guestbok)
VALUE ('".$_POST["guestbok"]."')";
$conn->query($sql);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
header('Location: /');
?>
Thanks in advance
/Daniel
Joining up raw bits of text and passing them on to your database to process is not a good idea. It opens up your system to SQL injection. While it's unlikely that someone could compromise your site when only INSERT statements are exposed in this way, it does mean that:
anyone with an apostrophe in their name will break the logic of the request
you are exposing a method by which someone can carry out a stored XSS attack by submitting javascript to your guestbook
Regarding the SQL Injection problem, there are 2 methods to protect your system - one is to transform the data in which a way that it cannot break the SQL string it is added to (e.g. using mysqli_real_escape_string()) but the recommended approach when using PDO to mediate your code's interaction with the DBMS is to use variable binding. Here you compose your SQL command with placeholders for the data and substitute them at run time.
If your ID is generated from a mysql auto insert id, then you can read the value from $conn->lastinsertid
$stmt=$conn->prepare("INSERT INTO user (firstname, lastname, email)
VALUES (:fnm,:lnm,:eml)");
$stmt->execute(array(
':fnm' => $_POST["first_name"],
':lnm' => $_POST["last_name"],
':eml' => $_POST["email"]));
$id=$conn->lastinsertid();
Your next problem is how to communicate this securely to the page where the user submits their guestbook comment (in your example code you try to do both operations in the same page).
Sending it in a round trip to the browser, as a cookie or as form variable means that it could be tampered with. There are esoteric stateless solutions where you can do this but with the data encrypted or cryptographically signed, however the simplest solution is to use sessions - add session_start() at the top of all your pages and any data you want available across requests can be stored in the $_SESSION superglobal.
(there are security issues relating to sessions as well)
When you receive the POST containing the guestbook data, then you should use an UPDATE user SET guestbook=:gstbk WHERE id=:id_from_session (or you could INSERT it into a seperate table with id as a foreign key)
Lastly, when you output the message the person left in your guestbook, make sure you protect the browser from any nasties in there:
print htmlentities($guestbook);
Ok, probably I managed to get what you need. Put the following two lines in your dbconfig.php:
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and then require it wherever you need a database connection:
file one:
require('dbconfig.php');
$sql = "sql 1";
$conn->query($sql);
then in another file
require('dbconfig.php');
$sql = "sql 2";
$conn->query($sql);

How do I connect to a database I created in HostGator?

Edit: I have googled and searched, read what I could find of their documentation. Even chatted with them. The chatter could help me. This is why I reach to you.
I am a complete beginner and I am having some troubles getting started with databases on hostgator. I guess my question also is valid using other hosts.
I created a db through the cpanel in hostgator and added a user to it.
I copied this script into a test.php in my /public_html/ folder and ran it on my site.
In the script I used the name, user and password from the database and user I previously created in cpanel. This database I can see using phpMyAdmin.
<?php
try
{
//open the database
$db = new PDO('sqlite:localhost;dbname=user_db', 'user_username', 'password');
//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");
//insert some data...
$db->exec("INSERT INTO Dogs (Breed, Name, Age) VALUES ('Labrador', 'Tank', 2);".
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Husky', 'Glacier', 7); " .
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Golden-Doodle', 'Ellie', 4);");
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Breed</td><td>Name</td><td>Age</td></tr>";
$result = $db->query('SELECT * FROM Dogs');
foreach($result as $row)
{
print "<tr><td>".$row['Id']."</td>";
print "<td>".$row['Breed']."</td>";
print "<td>".$row['Name']."</td>";
print "<td>".$row['Age']."</td></tr>";
}
print "</table>";
// close the database connection
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
This worked, which is nice, but it created a file in my /public_html/ folder called 'localhost;dbname=user_db'
My issue is that I thought I was connecting to the database I created using cpanel, but when I open phpMyAdmin, that database is empty.
How do I change that script to talk to the database I created using cpanel so that I can reach it using phpMyAdmin?
Edit 2:
So I learned that I need to use mysql, not sqlite because phpMyAdmin is based on MySQL.
Also, using the script from http://www.w3schools.com/php/php_mysql_create_table.asp I was able to connect! So, success! Thank you #mituw16 and #Fred -ii- for helping me! :D
I am assuming you created a MySQL database if you used PHPMyAdmin even thought the tags say SQL Lite.
It looks like you're trying to create an SQL Lite database instead of opening a connection to your MySQL database.
Change this line to the following
//open the database
$db = new PDO('mysql:localhost;dbname=user_db', 'user_username', 'password');

php mysql Insert into not working

So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote

MYSQL slow queries with PHP

I'm using mysql and php for registration on my web-site. Registration is ok. Mysql do queries immediately. But in login there strange things begin to happen. I insert a test in my php code to insert test row to database. First test code inserted immediately, but 2nd was inserted after series of refresh and relog actions only after 10 minutes. The 3rd test query is the same-after approximately 10 minutes after 2nd query.
Here is login code:
<?php
session_start();
if(isset($_SESSION['id'])){
echo 'You have logged in.';
echo $_SESSION['id'];
}
else {
$email=$_POST['email'];
$password=$_POST['password'];
$db=new mysqli('','','','');
if (mysqli_connect_errno()) {
echo 'Unable to connect to database: '.mysqli_connect_error().'. Please e- mail our system administrator. We will fix this error as soon as possible. Thanks for patience and understanding. ';
exit();
}
//TEST QUERY
$query="insert into test values(3, 'test')";
$result=$db->query($query);
//LOGIN QUERY
$query="select id from users where email='$email' and password='$password'";
$result=$db->query($query);
if ($result->num_rows==0) {
echo 'Incorrect email or password.';
}
else {
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
echo 'You have logged in.';
echo $_SESSION['id'];
//THIS TEST QUERY IS NOT IMPLEMENTED
$query="insert into test values(1, test)";
$result=$db->query($query);
}
}
?>
Where is mistake?
Test table consists of 2 columns: id (medium int, primary key, unsigned) and test(text)
Thanks in advance.
Sounds like the cookie could be expiring after 10 minutes. Run echo session_cache_expire(); to see what your expiration time is set to. More details at http://php.net/manual/en/ref.session.php
insert into test values(1, test)
-- test -- needs quotes or you are going to get an error that the column test doesn't exist (unless it does). If it does exist, it's probably going to be empty, as mysql probably doesn't know what you mean by test -- maybe your version thinks it's a constant or something.
If you posted what the table structure of your test table is, that would help solve it probably.
This looks suspicious to me.
$query="insert into test values(3, 'test')";
Is it trying to set the ID of every row inserted to 3? ID's have gotta be unique.
EDIT:
This probably won't fix your problem, but it will make your life easier by not forcing you to manually change ID's each time.
INSERT INTO test SET <colname>='test'
where <colname> is the name of the column that "test" is going into.
Just a little security hint: your SQL queries are very dangerous as they are prone to SQL injection attacks. See the Wikipedia article for alternatives ...

Categories