Have a simple registration form that is being linked to a php file in order to send the info to a database but everytime i try it the data isnt showing up in the phpMyAdmin database??
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$number = $_POST['number'];
$email = $_POST['email'];
$details = $_POST['details'];
$user="root";
$password="secure";
$database="darrenweircharity";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die ("Unable to select database");
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('$name', '$address', '$number', '$email', '$details' NOW())";
mysql_query($query);
mysql_close();
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try with:
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('" . $name . "', '" . $address . "', '" . $number . "', '" . $email . "', '" . $details . "');";
You have NOW() at the end of the query that shouldn't be there.
Also note that your code has an SQL injection vulnerability (see mysql_real_escape_string()), I suggest you to prepare queries via PDO.
protect from possible SQL injection:
$name = mysql_real_escape_string($name);
$address = mysql_real_escape_string($address);
$number = mysql_real_escape_string($number);
$email = mysql_real_escape_string($email);
$details = mysql_real_escape_string($details);
replace with:
$query = "
INSERT INTO registrationdetails (`name`, `address`, `number`, `email`, `details`)
VALUES ('$name', '$address', '$number', '$email', '$details')");
$query = "
INSERT INTO registrationdetails (name, address, number, email, details, date_time)
VALUES ('{$name}', '{$address}', '{$number}', '{$email}', '{$details}', NOW())
";
Replace the date_time with your column_name. And remember to escape all submitted values with mysql_real_escape_string before inserting them into the database.
Related
I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);
I hope this isn't a repeat question. I have searched all over to find an answer to no avail.
I want to insert into a row of a table. It sounds simple enough, but if the table is empty, it will not work. I can't figure out why. As long as there is one row in the table, it works fine. Any help is appreciated. Thanks.
My code:
<?php
$fname = $_POST['fname'];
$mi = $_POST['mi'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$con = mysqli_connect("localhost","database_username","database_password","database");
$sql1 = "INSERT INTO employee (fname, mi, lname, phone, email, add1, add2, city, state, zip) VALUES ('$fname', '$mi', '$lname', '$phone', '$email', '$add1', '$add2', '$city', '$state', '$zip')";
mysqli_query($con,$sql1);
mysqli_close($con);
?>
Your code is correct but it may some times data have some special characters such as \ / ? etc. thus suggest you to change all variable of the code from
$fname = $_POST['fname'];
to
$fname = addslashes($_POST['fname']);
then try it it will be done
You are not escaping the values. If any value contains an apostrophe, your query will faile. Since they come from post you must use mysqli_real_escape_string.
use following execute to insert a row
mysqli_query($con,$sql1);
musqli_execute($sql1);
I made it work after many hours of trying everything I could think of to do... Ultimately, I ended up checking for an empty table first, and then re-creating the table if it was empty.
I'm not sure why this works, but this is my code... it's a bit inelegant, but I could find no better solution. I know that I have not escaped my values. I will later. For now, I simply wanted to solve this problem that I have been wracking my brain about for days.
<?php
$fname = $_POST['fname'];
$mi = $_POST['mi'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE TABLE employee'
. ' ('
. ' fname text,'
. ' mi varchar(1),'
. ' lname text,'
. ' email varchar(100),'
. ' phone varchar(15)'
. ' add1 varchar(100),'
. ' add2 varchar(100),'
. ' city varchar(100),'
. ' state varchar(25)'
. ' zip varchar(10),'
. ' );';
$sql1 = "INSERT INTO employee (fname, mi, lname, phone, email, add1, add2, city, state, zip,) VALUES ('$fname', '$mi', '$lname', '$phone', '$email','$add1', '$add2', '$city', '$state', '$zip')";
$sql2 = "SELECT * FROM employee";
$sql3 = mysqli_query($con,"SELECT count(*) FROM employee");
if ($sql3 == FALSE) {
trigger_error(mysql_error()." in ".$sql3);
exit();
}
else
{
$result = mysqli_fetch_array($sql3);
}
if($result[0] != 0)
{
mysqli_query($con,$sql1);
}
else
{
mysqli_query($con,$sql);
mysqli_query($con,$sql1);
}
mysqli_close($con);
?>
if variable is a string use '".$fname."' foreach variable in query
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
if($email)
{
$connect = mysql_connect(" HOST ", " USERNAME ", " PASSWORD") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', 'random_string(10)')";
$result = mysql_query($query) or die("Some kind of error occured.");
echo ("Welcome " + $username + ", you are now in my database!");
}
else die("You did not fill out the fields correctly, please try again.");
?>
I need help with the line in the middle that starts with $query = "INSER ... 'random_string(10)')";
I need a random alphanumeric string to be inserted into the table called "customers" but instead of calling the function "random_string()" it inserts "random_string(10)" into my table which gives me this for my table with 6 fields:
5 John Smith Jogsz#CiniCraft.com random_string(10) 0
How do I fix this?
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) . "')";
This should work!
I think that even though double quotes will parse variables, they wont parse functions.
concatenate the function and your string,
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) ."')";
As a sidenote, the query is vulnerable with SQL Injection if the values of the variable came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
make two statements of it. In the first statement you call your function and assign the value to a variable and then in your INSERT... statement you use the variable
I am receiving the following error from the code below.
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 '#doe.com,username,5f4dcc3b5aa765d61d8327deb882cf99,09/05/2011 1:11:13 AM)' at line 1
$username = $_GET['username'];
$password = md5($_GET['password']);
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$email = $_GET['email'];
$date = uk_date();
$conn = mysql_connect('localhost', 'myuser', 'mypass');
mysql_select_db('dbname');
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES (". $firstname . ",". $lastname ."," . $email . "," . $username . "," . $password . "," . $date . ")";
$result = mysql_query($query) or die(mysql_error());
echo 'Success';
mysql_close($result);
Please could you let me know what my problem is? I am new to MySQL and PHP so please can you provide an explanation to what I have done wrong for later reference.
You haven't quoted any of the values in your INSERT, you should be saying something more like this:
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" . $username . "','" . $password . "','" . $date . "')";
You should also be using mysql_real_escape_string on all those variables to make sure that any embedded quotes and such are properly encoded.
A better version would be something like this:
$query = sprintf("INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname),
mysql_real_escape_string($email),
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($date));
You should also listen to BoltClock and use PDO and placeholders so you don't have to worry about your quotes and escaping so much. PDO will also make it easier to switch databases.
Probably user input have a single quote character, so it will be safe to escape special character before send it as query to database, this will prevent your script from sql injection.
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('$firstname', '$lastname', '$email','$username','$password', '$date')";
Once you have escaped your variables like suggested by other, you need to surround them with quotes if they are string varialbles :
mysql_select_db('dbname');
$query = "INSERT INTO accounts
(FirstName, LastName, Email, Username, Password, LastLoginDate)
VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" .
$username . "','" . $password . "','" . $date . "')";
$result = mysql_query($query) or die(mysql_error());
echo 'Success'; mysql_close($result);
In this case i added single quotes. you shouldnt have any errors now
I'm trying to insert a value into my sql table that has html in it: like follows
<?
$story ="<div class='post'><p class='date'>$mont<b>$day</b></p><h2 class='title'>lkjljt</h2><p class='meta'><small>Posted $name | $school, $date | Rating</small></p><div class='entry'>$message</div></div>";
$db = mysql_connect("host", "user", "password");
mysql_select_db("db", $db);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story', '$school','$location', '$sex', '$zipcode', '$name');";
$result = mysql_query($sql);
if($result)
{ $success = " Your hookup has been submitted ";}
else{
$error = "something went horribly wrong" . mysql_error();}
?>
I keep getting a syntax error when I submit this page, and if I comment $story out, the query runs fine. How can I fix this?
The most likely reason is that $story contains single quotes, which will break the query.
Protect it using mysql_real_escape_string
In general, this is a bad idea as it is open to SQL injection.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story',
'$school','$location', '$sex', '$zipcode', '$name');";
At least, use mysql_real_escape_string which will protect the input for characters that have special meaning in a MySQL query. Use it on all textual columns.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '" .
mysql_real_escape_string($story) . "','".
mysql_real_escape_string($school) . "','".
mysql_real_escape_string($location) . "', '$sex', '$zipcode', '" .
mysql_real_escape_string($name) ."');";
If you didn't care about SQL Injection ( though I dont know why would you wouldnt ) you could also use htmlspecialchars to fix your problem. mysql_real_escape_string is obviously the better choice though like #cyberkiwi said