Use a $variable inside a SQL string? - php

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"

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]')";

Sending to SQL database via the URL

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')";

How to fix php adding a plain row

I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.

PHP attempt to update a MySQL database doesn't update anything

I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()

PHP and MySql trouble

I am having trouble making this seemingly simple MySql query work. Can anyone spot the problem?
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES (".$offerid.",".$ip.")");
?>
You probably want some single quotes:
"INSERT INTO voted (offerid,ip) VALUES ('" . $offerid . "','" . $ip . "')"
You should also use intval and mysql_real_escape_string to avoid SQL injection vulnerabilities:
$sql = "INSERT INTO voted (offerid,ip) VALUES (" .
intval($offerid). ", '" .
mysql_real_escape_string($ip) . "')";
Another alternative which may be easier to read is to use sprintf:
$sql = sprintf("INSERT INTO voted (offerid, ip) VALUES (%d, '%s')",
$offerid, mysql_real_escape_string($ip));
To place a string value into query, you must perform 2 actions on it:
enclose it in quotes
and escape special characters.
So, query must be like this:
INSERT INTO voted (text) VALUES ('I\'m a programmer')
Armed with this knowledge, you can easily write a code to make valid query:
$offerid = mysql_real_escape_string($_POST["offerid"]);
$ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
$sql = "INSERT INTO voted (offerid,ip) VALUES ('$offerid','$ip')"
mysql_query($sql) or trigger_error(mysql_error().$sql);
Note the trigger_error part.
It will provide you with comprehensive information on any error
my guess would be with quotes
mysql_query("INSERT INTO voted (offerid,ip) VALUES (\"".$offerid."\",\"".$ip."\")");
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES ('".mysql_real_escape_string ($offerid)."','".mysql_real_escape_string ($ip)."')");
?>
This adds the single quote marks around the strings you are inserting - as well as mysql_real_escape_string php function that will escape (add a backslash infront of) any security risk characters.
In addition to using intval(...) and mysql_real_escape_string(...) you could use parameterized statements (or placeholders) using PEAR::DB or PEAR::MDB2:
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn); // using PEAR::DB, though it's been superseded
if (DB::isError ($conn)) {
die ("Cannot connect: " . $conn->getMessage () . "\n");
}
$result =& $conn->query ("INSERT INTO voted (offerid,ip) VALUES (?,?)", array($_POST["offerid"], $_SERVER["REMOTE_ADDR"]));
if (DB::isError ($result)) {
die ("INSERT failed: " . $result->getMessage () . "\n");
}
Using placeholders and parameters is pretty common on platforms other than PHP, so it's not a bad idea to understand the basic premise behind them.
If you're interested in using DB modules like these, I'd recommend checking out Writing Scripts with PHP's PEAR DB Module by Paul DuBois. Again, the module it describes is superseded, but I find it's nonetheless interesting and informative.

Categories