PHP and MySql trouble - php

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.

Related

Unable to INSERT data into MySQL through HTML form using PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
Here is my Form:
<html>
<head>
<title>Stats</title>
</head>
<body>
<h2>Member Information Form</h2>
<form action="submit_mbr_nfo.php" method="post">
Member ID <input type ="text" name= "mbrid"/><br>
Member Name <input type="text" name="mbrnm"/><br>
Actual Name <input type="text" name="atlnm"/><br>
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here is my PHP file:
<?php
//Define database properties in global variables
define('DB_NAME', 'STATS');
define('DB_USER', 'root');
define('DB_PASSWORD', 'Test');
define('DB_HOST', 'localhost');
//store connection props in var
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//check connection
if (!$link) {
die ('Could not connect to the Database: ' . mysql_error());
}
//map $_POST to vars
$mbr_id = mysql_real_escape_string($link, $_POST['mbrid']);
$mbr_nm = mysql_real_escape_string($link, $_POST['mbrnm']);
$atl_nm = mysql_real_escape_string($link, $_POST['atlnm']);
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
mysql_select_db('STATS');
$exe_query = mysql_query( $sql, $link);
?>
And here is my php error log:
PHP Parse error: syntax error, unexpected '$mbr_id' (T_VARIABLE) in /Applications/MAMP/htdocs/stats/submit_mbr_nfo.php on line 21
I am very new and learning PHP and HTML, i tried several online solutions but nothing has worked so far. I am able to insert into DB if I don't use $_POST, i.e., manually typing in the values in php code, but that's not the goal, the goal is to use Form to populate MySQL DB. Any help is appreciated, thank you.
Try following query
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm','$atl_nm')";
You are having issues with string concatenation and quotes. Try following query:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
if you set primary key and auto increment on database for member id
so it very easy.you are not write mbr_id in query
$query="INSERT INTO MBR_NFO (MBR_NM,ATL_NM) VALUES( '$mbr_nm','$atl_nm')";
it's simple way
if you want not set primary key and autoincrement and try this code
$query ="INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM). VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
You should use prepared statements (see below) instead of manually concateting the query string. But, since you’re new to PHP, let us first fix your code. The line
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
has a couple of flaws. In PHP, string concatenation is done via the dot . operator, which you have used only partly. In order to construct the query string $sql, you have to add a couple of dots:
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (' . $mbr_id . ', ' . $mbr_nm . ',' . $atl_nm . ')';
While this is valid PHP syntax, it is still no valid SQL. If your user input is $mbr_id = 42, $mbr_nm = 'amit', $atl_nm = 'Amit Kumar', then after concatenation, $sql looks like
INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (1, amit, Amit Kumar)
and is missing quotes around the strings amit and Amit Kumar. At best, this makes your query invalid; at worst, it makes your query prone to injection attacks. Therefore, build your query using
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ("' . $mbr_id . '", "' . $mbr_nm . '","' . $atl_nm . '")';
or, because in PHP, variables in strings that are quoted with double quotes – e.g. "my name is $name", but not 'my name is $name' – are evaluated:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm,'$atl_nm')";
By far the best practise, however, is using prepared statements and parameterized queries:
$con = new PDO('mysql:host=localhost;dbname=STATS', 'root', 'Test');
$stmt = $con->prepare('INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (:mbr_id, :mbr_nm, :atl_nm)');
$stmt->bindValue(':id', $mbr_id);
$stmt->bindValue(':mbr_nm', $mbr_nm);
$stmt->bindValue(':atl_nm', $atl_nm);
$stmt->execute();

Invalid query: You have an error in your SQL syntax

<?php
mysql_connect("mysql6.000webhost.com","a6124751_murali1","***");
$db= mysql_select_db("a6124751_signup");
$topic=$_GET["Topic"];
$question=$_GET["Question"];
$company =$_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ($topic, $question, $company)";
$sql1=mysql_query($query);
if (!$sql1) {
die('Invalid query: ' . mysql_error());
}
?>
this is my php code in server where there is a table named 'questions' and i am trying to insert the data into it from the input got from the GET method using form at front end, i can figure out that data is coming properly from the client which i have checked using echo. I am getting an error as
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 'name, type your question here, company)' at line 1
Don't know what is the error in the query. anyone find it out asap. thank you
You need to quote your values
('$topic', '$question', '$company')
since those are strings.
Plus, you should escape your data for a few reasons. Not let MySQL complain about certain characters such as hyphens etc., and to protect against SQL injection.
Use prepared statements:
https://en.wikipedia.org/wiki/Prepared_statement
Reference(s):
https://en.wikipedia.org/wiki/SQL_injection
How can I prevent SQL injection in PHP?
http://php.net/manual/en/function.mysql-real-escape-string.php
Edit:
As an example using your present MySQL API:
$topic = mysql_real_escape_string($_GET['topic']);
$question = mysql_real_escape_string($_GET['question']);
$company = mysql_real_escape_string($_GET['company']);
I don't know what your inputs are called, so that's just an example.
You mentioned about using $_GET for debugging but using a POST method.
Change all $_GET to $_POST above.
Try this
<?php
$db = mysqli_connect('mysql6.000webhost.com', 'a6124751_murali1', 'default#123', 'a6124751_signup');
if (!$db) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$topic = $_GET["Topic"];
$question = $_GET["Question"];
$company = $_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
$sql1=mysqli_query($db, $query);
if(!$sql1)
{
die('Invalid query: ' . mysqli_error($db));
}
?>
Fixes in your code
The mysql extension is deprecated and will be removed in the future:
use mysqli or PDO instead
You need to quote your values ('$topic', '$question', '$company')
You have to put the values in single qoutes, if that are char types:
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
But you should not longer use the deprecated mysql_*API. Use mysqli_* or PDO with prepared statements.

SQL Update code issue/PHP injection

I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";

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 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()

Categories