Sending to SQL database via the URL - php

I am having a little difficulty in saving values via the URL into a SQL database. I can explicitly put in values into the the INSERT command, but that is not what I want.
Say I had a URL like the following:
and code like the following:
<?php
include 'curr.php';
$url = curPageURL();
$query_str = parse_url($url, PHP_URL_QUERY);
$query = parse_str($query_str, $query_params);
$fn = $_REQUEST['Firstname'];$sn = $_REQUEST['Surname'];
$link = mysql_connect('server.co.li', 'username', 'pass333');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'INSERT INTO p_database '.
'(Firstname, Surname) '.
'VALUES ($fn, $sn)';
mysql_select_db('my_db');
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($link);
?>
I have tried $_Get and $_POST as well as $_REQUEST to get the information, and here is the error that is produced when I run:
"Connected successfullyCould not enter data: Unknown column '$fn' in 'field list'"
Any assistance would be appreciated.
(P.s. I know the code is not secure or safe, that will come after the functional parts are complete).

Your quotes are incorrect,
$sql = "INSERT INTO p_database ".
"(Firstname, Surname) ".
"VALUES ('$fn', '$sn')";
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. 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.

You need to escape your $fn and $sn like so:
$sql = "INSERT INTO p_database (Firstname, Surname) VALUES ('$fn', '$sn')";

Related

Having trouble getting two fields to concatenate

hostSo i know how to get the two fields to concatenate from directly inside of MYSQL, but having trouble getting it to work with my PHP.
Directly from MYSQL = SELECT CONCAT(ConfigurationItem, ' - ', ,Buzzword) FROM Buzz;
But how do i incorporate it into this PHP below, I have researched to no end. I want to combine the two fields ConfigurationItem and Buzzword into a field named shortdescription, without having to do it manually through MYSQL everytime the PHP is submitted.
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]','$_POST[TierStatus]','$_POST[MasterTicket]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I've concatenated them together in php as the insert.
Although there is nothing wrong with catting them in your select statement.
In fact I'd opt for that because it is redundnant-y, you are inserting the same data twice in essence.
But this should do what you are asking for.
I have also corrected your quotation marks in the query.
Also google sql injection
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword,
OccurrenceDate, PostingDate,
TierStatus, MasterTicket, shortdescription)
VALUES
('".$_POST['BuzzID']."','".$_POST['ConfigurationItem']."',
'".$_POST['Buzzword']."','".$_POST['OccurrenceDate']."','".$_POST['PostingDate']."',
'".$_POST['TierStatus']."','".$_POST['MasterTicket']."',
'".$_POST['ConfigurationItem']."' - '". $_POST['Buzzword']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I ended up resolving my issue by inserting "ShortDescription" in the INSERT INTO line and then just telling it to insert the two fields I wanted together in the field "ShortDescription" and by using double spaces between my hyphen, I was able to get the desired effect I was looking for which turns out like this "Example - Example" See my code below
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket, ShortDescription)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]',
'$_POST[TierStatus]','$_POST[MasterTicket]','$_POST[ConfigurationItem]' ' - ' '$_POST[Buzzword]')";

How do I submit form data to a database and redirect someone to URL?

PHP Newbie here: Quick question on forms and php,
Form in Html page
<form class="form" id="form" onsubmit="return validateForm()" method="post" action="submitdatabase.php">
I can insert data into my database successfully but how do I direct them to a certain URL as well?
If it helps, below is my PHP, needless to say it doesn't work:
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES ('$_POST[fname]','$_POST[lname]','$_POST[address]','$_POST[phone]','$_POST[email]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con)
header("Location: URLREDIRECTION.com")
?>
PHP Newbie.. this should work
always use this to escape strings mysql_escape_string($var);
also mysql_connect() is depreciated, use mysqli_connect('host', 'user', 'password', 'database') instead.
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$fname = mysql_escape_string($_POST['fname']);
$lname = mysql_escape_string($_POST['lname']);
$address = mysql_escape_string($_POST['address']);
$phone = mysql_escape_string($_POST['phone']);
$email = mysql_escape_string($_POST['email']);
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES
('$fname','$lname','$address','$phone','$email')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: http://yoursite.com");
This code... is... a bit of a mess and old. First things first: don't use mysql_* functions. Also you must escape your user's data for sure. To simplify both in one, I will work with PDO. Here you have a tutorial (just click here). Also, as other stated, you also needed to close a couple of semicolons.
<?php
/* Create a PDO object */
$DB = new PDO("mysql:host=localhost;dbname=database",'root','');
/* Prepare the statement you want to do, in this case, an INSERT */
$con = $DB->prepare("INSERT INTO leads (fname, lname, address, phone, email)
VALUES (?,?,?,?,?)");
/* Execute the previous statement with the corresponding values for each '?' */
$con->execute(array($_POST['fname'],
$_POST['lname'],
$_POST['address'],
$_POST['phone'],
$_POST['email']));
/* Redirect the user */
header("Location: http://www.example.com/");
?>
Obviously this is not secure. The OP knows this and has chosen to do
things this way. If he genuinely wants to do things deliberately
wrong I have no problem with that.
Anyone else reading this answer should keep in mind that this is
horrible practice and I have only given it as an answer because it is
clearly what he wanted. Do not use this.
In an actual application, you should be at the very least using mysql_real_escape_string() to escape the $_POST variables from
user input, or (much) better yet, use MySQLi or PDO in conjunction
with prepared statements, to eliminate the chances of SQL injection.
You were missing a semicolon.
Also, you changed the header line instead of leaving somewhere you were trying to redirect to there. How are we supposed to debug a script that we can't even see? Try it as posted here and see if it takes you to google. If not then there's something else going on. If it does, you typed out the header() function wrong but we couldn't tell, because you didn't show it to us.
Try this:
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[address]','$_POST[phone]','$_POST[email]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: http://www.google.com");
?>
Also, as a few people have pointed out already mysql() functions are officially depreciated. Although it should be working anyway.
try this..this will work 100%
<?php
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$phn=$_POST['phn'];
$email=$_POST['email'];
$street=$_POST['street'];
$city=$_POST['city'];
$state=$_POST['state'];
$con=mysqli_connect('localhost','root','','database');
$insert= "INSERT INTO table (id,name,phone,email,street,city,state) VALUES('','$fname $lname','$phn','$email','$street','$city','$state')";
$run=mysqli_query($con,$insert);
if($run)
{
header('location:https://google.com');
}
?>
You have a syntax error here:
mysql_close($con)
You need to add a semicolon:
mysql_close($con);
If your script produces any output before the header() statement, the redirect will not happen. Warnings, errors, and intentional output will all cause your header() statement to fail.
If you are redirecting to another site, consider use the 'http://' or 'https://' prefix for clarity:
header("Location: http://urlredirection.com");
If you are redirecting to your own site, just use a leading slash:
header("Location: /your/url.php");
Finally, consider updating your code to use mysqli or PDO instead of the deprecated mysql_* functions.

What is wrong with my MySQL query?

So, I have a form that posts to my php file using ajax, and succeeds. But the following query doesn't insert anything. Can someone help me understand what I'm doing wrong?
My php file:
<?php
include 'connect.php' ;
$type = mysql_real_escape_string($_POST['type']);
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
if ($type == 'Just Text') {
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());
}
?>
My connect.php:
<?php
$dbhost = "localhost";
$dbname = "example";
$dbuser = "test";
$dbpass = "test";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
If you aren't receiving any errors and the INSERT just doesn't happen, it is most likely because the if statement fails to be true. Verify that $type actually matches Just Text.
You should also be inserting values using prepared statements, and use PDO or MySQLi - this article will help you decide which.
first, echo "something" after the if statement and recall the data with your ajax post. you can find out if your if statement is working, then try formatting your variables like so
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('$title', '$type', 0, '$content')")or die("MySQL Error: " . mysql_error());
I just want to throw in an official vote/recommendation in favor of switching to a parameterized SQL statement, too. In spite of the use of mysql_real_escape_string, schlepping a SQL statement together via string concatenation is neither necessary nor a good idea. Honestly, I find a prepared statement much, much easier to read than the typical string-concatenation exercise, as well:
$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
$stmt->execute(array($username, $password));
Alright, it was a stupid mistake on my side. There were columns I didn't include and they were not being assigned a value. Thanks everyone for helping out.

Use a $variable inside a SQL string?

I would like to be able to select a category from a dropdown and depending on the category it will add it to whatever SQL table is it equal with.
<?php
$article = $_POST['article'];
$con = mysql_connect("******","******","*******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jstaltso_staltsoft", $con);
$sql="INSERT INTO $article (headline, content)
VALUES ('$_POST[headline]', '$_POST[content]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Content Added!";
echo "<br/>";
echo "<a href='articles.php'><- Back</a>";
mysql_close($con)
?>
I want the variable $articles to be in the place of where you out the name of the table.
$sql="INSERT INTO $article (headline, content)
VALUES ('$_POST[headline]', '$_POST[content]')";
So whatever I choose in the dropdown, it will put it at $articles.
Try:
"INSERT INTO `{$article}` ...."
Don't forget to sanitize your input! (mysql_real_escape_string, for starters)
You cannot use that type of variables, change last code to
$sql="INSERT INTO $article (headline, content)
VALUES ('" . $_POST['headline'] " . ', '" . $_POST['content'] . "')";
I know this answer won't be too helpful for you right now, but sice there is just too much wrong with that code and that approach, here are a few tips:
Use PDO instead of PHP's MySQL functions. It'll seem daunting at first, especially if you haven't got any experience with object-oriented programming, but it's definately worth the effort.
Sanitize that $article value! if($article == 'foo' || $article == 'bar') {...}
The best ways to use variables in strings are: "This is a ".$adjective." string" and "This is a {$adjective} string"

PHP post error Mysql

I am trying to post data to my database using the following code:
<?php
if(isset($_POST['add']))
{
$dbhost = 'internal-db';
$dbuser = 'support';
$dbpass = 'sgh';
$db = "mpc";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$message = $_POST['message'];
$callback = $_POST['callback'];
$sql = "INSERT INTO enquiries
(firstname, surname, email, phone, country, message, callback)
VALUES('$firstname','$surname', $email, $phone, $country, $message, $callback)";
mysql_select_db($db);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
When I try to post the form I revieve the following error:
Could not enter data: 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 ' , , , )' at line 3
Can't work out what is wrong in the code. Can you help???? Am I using deprecated code??
The variables in your query are empty ($email, $phone, $country, $message, $call). Try to do var_dump of the variables before the query and see if they have some value. Also you need to wrap them with quotes like '$var' when they are strings, such as a mail.
Also, for the love of god, sanitize the input. See here:
What are the best PHP input sanitizing functions?
How can I prevent SQL injection in PHP?
You have to put the single quote around the string columns even if they are blank or contain value.
$sql = "INSERT INTO enquiries
(firstname, surname, email, phone, country, message, callback)
VALUES('$firstname','$surname', '$email', '$phone', '$country', '$message', '$callback')";
Do not forgot to use mysql_real_escape_string on the data.
You haven't encapsulated your fields in quotes. E-mail address (amongst others) without quotes will make your INSERT statement invalid.
Besides that, you should always escape the input, because the input can contain invalid characters, or worse, it can contain malicious code that may destroy your data!
So:
if (array_key_exists($_POST, 'email')) {
$tmpemail = (string)$_POST['email'];
// Optional additional checks for pattern matches go here..
// if all tests succeed, escape special characters and assign value:
$email = mysql_real_escape_string($tmpemail);
}
// Similar checks for other values
if ((isset($email) && isset($fielda) && isset($fieldb) ... )
{
$query = "
INSERT INTO YourTable(fielda, fieldb, email, ...)
VALUES('valuea', 'valueb', '$email', ...)";
}
else
{
// Some values missing. Handle appropriately.
}

Categories