My update form script works only, if I use numbers but, if I try use any words it won't work. I need help, thanks!
<?php
if(isset($_POST['teams'])){
$home_team = $_POST['home_team'];
$visitor_team = $_POST['visitor_team'];
$sql = mysql_query("UPDATE table1
SET home_team = $home_team, visitor_team = $visitor_team
WHERE active = 1") ;
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die("<p>Error! Could not update team names. Click return button.</p>");
}
echo "<p>Team names set successfully!</p>";
mysql_close($conn);
}
?>
try with use of '' into your query,
$sql = mysql_query("UPDATE table1 SET
home_team = '".mysql_real_escape_string($home_team)."',
visitor_team = '".mysql_real_escape_string($visitor_team)."'
WHERE active = '1'") ;
also add mysql_real_escape_string() to prevent from SQL Enjection..
Every string passed to a SQL statement must be enclosed within a ''; if they are not, it will result in an error.
That being said, throwing content straight from a form into the database is very, very, very, very (I need another very) bad. Your database can simply be wiped by anyone; it's called SQL injection
To protect your database, you can start with this good article on PDO
Related
trying to submit data from a form but does not seem to be working. Can't spot any problems?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proId = $_POST["id"];
$proCode = $_POST["code"];
$proDescr = $_POST["descr"];
$proManu = $_POST["manu"];
$proCPU = $_POST["cpu"];
$proWPU = $_POST["wpu"];
$proBarCode = $_POST["barcode"];
$proIngredients = $_POST["ingredients"];
$proAllergens = $_POST["allergenscon"];
$proMayAllergens = $_POST["allergensmay"];
//Insert users data in database
$sql = "INSERT INTO prototype.Simplex_List (id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay)
VALUES ('$proId' , '$proCode', '$proDescr' , '$proManu' , '$proCPU' , '$proWPU' , '$proBarCode' , '$proIngredients' , '$proAllergens' , '$proMayAllergens')";
//Run the insert query
mysql_query($sql)
First and foremost, please do not use mysql_*** functions and please use prepared statements with
PDO http://php.net/manual/en/pdo.prepare.php
or mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php instead. Prepared statements help protect you against sql injection attempts by disconnecting the user submitted data from the query to the database.
You may want to try using mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php to ensure no stray " or ' is breaking your query.
$proId = mysql_real_escape_string($_POST["id"]);
$proCode = mysql_real_escape_string($_POST["code"]);
$proDescr = mysql_real_escape_string($_POST["descr"]);
$proManu = mysql_real_escape_string($_POST["manu"]);
$proCPU = mysql_real_escape_string($_POST["cpu"]);
$proWPU = mysql_real_escape_string($_POST["wpu"]);
$proBarCode = mysql_real_escape_string($_POST["barcode"]);
$proIngredients = mysql_real_escape_string($_POST["ingredients"]);
$proAllergens = mysql_real_escape_string($_POST["allergenscon"]);
$proMayAllergens = mysql_real_escape_string($_POST["allergensmay"]);
Additionally ensure your form is being submitted by calling var_dump($_POST) to validate the data
You can also see if the query is erroring by using mysql_error http://php.net/manual/en/function.mysql-error.php
if (!mysql_query($sql)) {
echo mysql_error();
}
advices about PDO, prepared statements were done.
1) Do you have a database and connection to it?
Look at your prototypeconnect.php and find database name there. check that its name and password is similar that u have.
2) Do you have a table named prototype.Simplex_List in your database?
a) IF YOU HAVE:
check if your mysql version >= 5.1.6
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
b) IF YOU HAVE BUT ITS NAME is Simplex_List:
b-1) if your database name IS NOT prototype:
replace your
$sql = "INSERT INTO prototype.Simplex_List
with
$sql = "INSERT INTO Simplex_List
b-2) if your database name IS prototype:
you should escape your $_POST data with mysql_real_escape_string as #fyrye said.
c) IF YOU HAVE NOT:
you should create it
3) Check your table structure
does it have all theese fields id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay?
if you have there PRIMARY or UNIQUE keys you should be sure you are not inserting duplicate data on them
but anyway replace your
$sql = "INSERT INTO
with
$sql = "INSERT IGNORE INTO
PS: its not possible to help you without any error messages from your side
another day another question...
I need to write PHP script to update mySQL database.
For example: updating profile page when user want to change their first name, last name or etc.
Here is my php script so far, it doesn't work. Please help!
<?php
# $db = new MySQLi('localhost','root','','myDB');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$First_Name2 = $_POST['First_Name2'];
$query = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";
$result = $db->query($query);
if(! $result)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
$db->close();
}
?>
THank you.
Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.
e.g. consider submitting "Fred" as the first name:
$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";
now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:
$query = "UPDATE people SET First_name = '$First_Name2' ...";
You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.
In short, this code is pure cargo-cult programming.
OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition
I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );
So I've been trying to replicate a second order SQL Injection. Here's an example template of two php based sites that I've prepared. Let's just call it a voter registration form. A user can register and then you can check if you're a registered voter or not.
insert.php
<?php
$db_selected = mysql_select_db('canada',$conn);
if (!db_selected)
die("can't use mysql: ". mysql_error());
$sql_statement = "INSERT into canada (UserID,FirstName,LastName,Age,State,Town)
values ('".mysql_real_escape_string($_REQUEST["UserID"])."',
'".mysql_real_escape_string($_REQUEST["FirstName"])."',
'".mysql_real_escape_string($_REQUEST["LastName"])."',
".intval($_REQUEST["Age"]).",
'".mysql_real_escape_string($_REQUEST["State"])."',
'".mysql_real_escape_string($_REQUEST["Town"])."')";
echo "You ran the sql query=".$sql_statement."<br/>";
$qry = mysql_query($sql_statement,$conn) || die (mysql_error());
mysql_close($conn);
Echo "Data inserted successfully";
}
?>
select.php
<?php
$db_selected = mysql_select_db('canada', $conn);
if(!db_selected)
die('Can\'t use mysql:' . mysql_error());
$sql = "SELECT * FROM canada WHERE UserID='".addslashes($_POST["UserID"])."'";
echo "You ran the sql query=".$sql."<br/>";
$result = mysql_query($sql,$conn);
$row=mysql_fetch_row($result);
$sql1 = "SELECT * FROM canada WHERE FirstName = '".$row[1]."'";
echo "The web application ran the sql query internally=" .$sql1. "<br/>";
$result1 = mysql_query($sql1, $conn);
$row1 = mysql_fetch_row($result1);
mysql_close($conn);
echo "<br><b><center>Database Output</center></b><br><br>";
echo "<br>$row1[1] $row1[2] , you are a voter! <br>";
echo "<b>VoterID: $row[0]</b><br>First Name: $row[1]<br>Last Name: $row[2]
<br>Age: $row[3]<br>Town: $row[4]<br>State: $row[5]<br><hr><br>";
}
?>
So I purposely made this vulnerable to show how second order SQL Injection works, a user can type in a code into the first name section (where I am currently stuck, I've tried many different ways but it seems that I can't get it to do anything).
Then when a person wants to activate the code that he has inserted in the first name section, all he needs to do is just type in the userID and the code will be inserted.
For example:
I will type into the insert.php page as:
userid = 17
firstname = (I need to inject something here)
lastname = ..
age = ..
town = ..
state = ..
Then when I check for my details, and type in 17, the SQL script injected will be activated.
Can I get few examples on what sort of vulnerabilities I can show through this?
What is there to demonstrate?
Second order SQL injection is nothing more than SQL injection, but the unsafe code isn't the first line.
So, to demonstrate:
1) Create a SQL injection string that would do something unwanted when executed without escaping.
2) Store that string safely in your DB (with escaping).
3) Let some other piece of your code FETCH that string, and use it elsewhere without escaping.
EDIT: Added some examplecode:
A table:
CREATE TABLE tblUsers (
userId serial PRIMARY KEY,
firstName TEXT
)
Suppose you have some SAFE code like this, receiving firstname from a form:
$firstname = someEscapeFunction($_POST["firstname"]);
$SQL = "INSERT INTO tblUsers (firstname) VALUES ('{$firstname }');";
someConnection->execute($SQL);
So far, so good, assuming that someEscapeFunction() does a fine job. It isn't possible to inject SQL.
If I would send as a value for firstname the following line, you wouldn't mind:
bla'); DELETE FROM tblUsers; //
Now, suppose somebody on the same system wants to transport firstName from tblUsers to tblWhatever, and does that like this:
$userid = 42;
$SQL = "SELECT firstname FROM tblUsers WHERE (userId={$userid})";
$RS = con->fetchAll($SQL);
$firstName = $RS[0]["firstName"];
And then inserts it into tblWhatever without escaping:
$SQL = "INSERT INTO tblWhatever (firstName) VALUES ('{$firstName}');";
Now, if firstname contains some deletecommand it will still be executed.
Using a first name of:
' OR 1 OR '
This will produce a where clause in the second SQL of
WHERE FirstName = '' OR 1 OR ''
Therefore the result will be the first record in the table.
By adding a LIMIT clause, you can extract all rows from the table with:
' OR 1 ORDER BY UserID ASC LIMIT 0, 1 --
Obviously it will only extract 1 row at a time, so you would need to repeat that and increment the 0 in the LIMIT. This example uses a comment -- to terminate the remaining SQL which would otherwise cause the query to fail because it would add a single quote after your LIMIT.
The above is a simple example, a more complex attack would be to use a UNION SELECT which would give you access to the entire DB through the use of information_schema.
Also you are using addslashes() in one of your queries. That is not as secure as mysql_real_escape_string() and in turn: escaping quotes with either is not as secure as using prepared statements or parameterised queries for example in PDO or MySQLi.