I have a page that inserts records into a database file called ports that holds two fields, called id and port.
The data is checked by an include, checkform.php, that strips out any bad data and blank entries.
It works fine, and as I have more data files of a similar construction it seems logical to use the same page for inserting records by passing the file and field names to the page as parameters.
The SQL that is used for the stand alone page is:
$sql='INSERT IGNORE INTO ports(port) VALUES(?)';
I want to do some thing like:
$sql='INSERT IGNORE INTO $filename ($fieldname) VALUES(?)';
I have looked on the forum and found many solutions that do not appear to work
Like :
$sql='INSERT IGNORE INTO '$filename' ('$fieldname') VALUES(?)';
$sql='INSERT IGNORE INTO "'$filename'" ("'$fieldname'") VALUES(?)';
$sql='INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES(?)';
as well as :
$sql="INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES (`$fieldname`);";
and many others. The combination seems endless, and so far I would have been better just copying the pages and changing the variables by hand. The code for the insert is below:
// check if form submitted and has a value
If (isset($_POST['insert']))
{ require('../includes/checkform.inc.php');
// continue if the field is OK
if (empty($missing)) // ** missing is empty if the data is clean and exists
{ // process the input.
require_once('../includes/connection.inc.php');
// initialize a flag
$OK = false;
//create database connection
$conn = mysqli_connect( $DatabaseServer,$DatabaseUser, $DatabasePassword, $DatabaseName);
// Initialize prepared statement
$stmt = $conn->stmt_init();
//create SQL
$sql='INSERT IGNORE INTO ports(port) VALUES(?)'; //#
//bind parameters and execute statement
if($stmt->prepare($sql)) {
$stmt->bind_param('s',$_POST['port']);//#
$stmt->execute();
if ($stmt->affected_rows > 0)
$OK = true;
}//if $tmt
}// if empty
// redirect if successful or display an error - on page below
if ($OK) {
header('Location:insertok.php');
exit;
} else {
$error = htmlspecialchars($stmt->error);
The lines with //# against them are the ones that I need help with.
Most of the code is modified from a book by David Powers.
Howard Walker
To interpolate variables in a string, you have to use double quotes "$var". Note that you shouldn't surround $var with single quotes. And your table and column names might be one of the reserved words. It complains when that happens. You use backticks to escape the reserved words.
$sql="INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES (?);";
This should work just fine.
EDIT
Your file/field might also include the characters that mySQL doesn't like. In that case, escape the query string before executing it. Refer: http://us3.php.net/manual/en/mysqli.real-escape-string.php
$sql = $stmt->real_escape_string($sql);
Related
I am using the following code to insert in MYSQL table:
try{
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(':t_id',':t_name',':mem_id')";
$stmt=db::con()->prepare($sql);
$stmt->bindParam(':t_id',$tid,PDO::PARAM_INT);
$stmt->bindParam(':t_name',$tNm,PDO::PARAM_STR);
$stmt->bindParam(':mem_id',$mId,PDO::PARAM_INT);
$stmt->execute();
}catch(PDOException $ex){
die("Error occured:".$ex->getMessage());
}
$tid variable has value=1;
$tNm variable has value='CBSE';
$mId variable has value=9
when this piece of code is run then no error is generated but in MYSQL table i observe the field values as 't_id'=0, 't_name'=t_name, 'mem_id'=0.I just don't understand what is wrong with my code.However, one funny thing is that when i try to acomplish the same task using the below mentioned code, proper data is inserted into the table.The code is
$db= new Database();
$db->open();
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES('$tid','$tNm','$mId')";
$db->query($sql);
When using PDO to bind parameters, keep in mind that it appropriately quotes and escapes for you automatically. This means you need to remove the quotes from your VALUES statement, as follows:
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(:t_id,:t_name,:mem_id)";
I'm having trouble inserting my values from one page into another and then into the database its showing no errors either which is rather puzzling and not inserting into the database.
I pass the values over from a form via ajax and all the values needed are being sent over so I presume it has something to do with the values sent over from pminsert. Database is included and all my values are safe from sql injection. I've just put the needed code below.
pminsert
if($_POST['pmtoid']==$_SESSION['id']){
user_core::pmmessage("1",$_POST['pmfromid'],$_POST['pmtoid'],$_POST['pmnewmsg'],"../pm.php?id=".$_POST['pmtoid']."&id2=".$_POST['pmfromid']."",$date);
}else{
user_core::pmmessage("3",$_POST['pmfromid'],$_POST['pmtoid'],$_POST['pmnewmsg'],"../pm.php?id=".$_POST['pmfromid']."&id2=".$_POST['pmtoid']."",$date);
}
user_core::pmmessage
public function pmmessage($typeids,$creatorids,$targetusers,$contents,$url,$date){
global $mysqli;
$contents = $contents;
//$content = strip_tags($content);
if($contents>0){
$date=date('y:m:d H:i:s');
$insertmessage = "INSERT INTO messages(message_type_id,message_creator,message_target,message_content,message_throughurl,message_time) VALUES ($typeids,$creatorids,$targetusers,$contents,$url,$date)";
$add_message = mysqli_query($mysqli,$insertmessage)or die(mysqli_error($mysqli,$insertmessage));
Make sure auto-commit was enabled, else don't forget to commit or you'll never see your data updated. That would explain why there is no errors.
Something just came to mind and I'd like to bounce it off:
Say you have a user profile, with 10 fields that the user can edit, and not all of them are required. When issuing update commands, is it more efficient to either:
A) Collect all of the fields, filled in or not, and issue one all encompassing update statement to the server's DB
or
B) Use client side validation to check to see which fields have been filled out or changed, and have a selection of SQL methods that only send and update these fields
or
C) Create groupings, like "updateRequiredFields(...) and updateExtraFields(...)", which would issue one smaller transfer if the changes only belong in one group, however two transfers if both are edited
General consensus? Clearly option B is the far more verbose approach, I'm just wondering if it's worth coding it all out or if it'll actually make a noticeable impact on the server (think "scaled for big data").
You could do something like this on your DB update function:
public function updateFields(array $fields) {
$updateQuery = array();
foreach($fields as $fieldKey => $fieldValue) {
//if $fieldValue is false, leave it unchanged
if ($fieldValue !== false) {
//NOTE: make sure you escape this or use PDO
$updateQuery[] = $fieldKey . '=' . $fieldValue;
}
}
$query = 'UPDATE UserInfo SET ' . implode(",", $updateQuery) . ' WHERE ...';
}
You just need to build $fields array based on what was modified on client side and then pass in with either new value or with false if no change.
Trying to make my blog secure and learning prepared statements.
Although I set the variable, I still get all the entries from database. $escapedGet is real variable when I print it out. It's obviously a rookie mistake, but I cant seem to find an answer.
I need to get the data where postlink is $escapedGet not all the data.
$escapedGet = mysql_real_escape_string($_GET['article']);
// Create statement object
$stmt = $con->stmt_init();
// Create a prepared statement
if($stmt->prepare("SELECT `title`, `description`, `keywords` FROM `post` WHERE `postlink` = ?")) {
// Bind your variable to replace the ?
$stmt->bind_param('i', $postlink);
// Set your variable
$postlink = $escapedGet;
// Execute query
$stmt->execute();
$stmt->bind_result($articleTitle, $articleDescription, $articleKeywords);
while($stmt->fetch()) {
echo $articleTitle, $articleDescription, $articleKeywords;
}
// Close statement object
$stmt->close();
}
just tryed this: echo $escapedGet;
echo $_Get['artcile']
and got - some_other
thats the same entry that I have saved in database as postlink
tried to shande postlink to id, and then it worked. but why not with postlink tab?
When you are binding your data using 'i' modifier, it gets bound as integer.
Means string will be cast to 0 in the final statement.
But as mysql does type casting, your strings become zeroes in this query:
SELECT title FROM post WHERE postlink = 0;
try it and see - for the textual postlinks you will have all your records returned (as well as a bunch of warnings).
So, bind strings using s modifier, not i
original post:
My script is not working (it's not recording the data). It was working before I added the mysql_real_escape_string, so I'm wondering if maybe I have not implemented it correctly:
$array = json_decode($downstream,TRUE);
$name = $array["status"]["name"];
$title = $array["status"]["title"];
$table = "mrTable";
$insert = "INSERT INTO $table (name, title) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($title)."')";
Does that implementation at INSERT look correct to you?
UPDATE:
Here is the entire code, hopefully this will help. It is still not working though. When the real_escape_string function is used, NONE of the data elements get recorded in the database. As soon as I remove the escape function, data is written fine (unless of course an apostrophe shows up).
Here we go:
//read contents of this file:
$json_data = file_get_contents('../list.txt');
//json to a php array
$array = json_decode($json_data,TRUE));
//store in mysql table
$table = "table1";
$name = mysql_real_escape_string($array["current"]["name"]);
$code = mysql_real_escape_string($array["current"]["code"]);
$insert="INSERT INTO $table (name, code) VALUES ('$name', '$code')";
$con = mysql_connect($db, $user, $pass);
if (!$con)
{
die ('Could not connect: ' . mysql_error());
};
mysql_select_db($yup, $con);
mysql_query($insert) OR die(mysql_error());
mysql_close($con);
UPDATE 2
Fixed! You need to connect to the database before first mentioning mysql_real_escape_string. Everything is working now...no blank data.
You need to be connected to a database to use mysql_real_escape_string. You don't seem to be. Make sure mysql_connect is over your line where you define $insert
Never insert values directly into a query string! Even if they are escaped, it's not a smart idea. Instead, use parametrised statements as such, which will render attacks like ' OR 1 = 1-- useless. You don't need to escape values for parametrised statements either...
PREPARE statement FROM
'INSERT INTO table (col1, col2)
VALUES
(?, ?)'
EXECUTE statement USING ('val1', 'val2')
DEALLOCATE statement
Deallocate only when you're done. You can re-execute as many times as you'd like with different values. If you are going to re-execute anyways, there is a gain in performance as well from doing it this way! (Because the statement is only prepared once for an infinite number of executions.) I advise you to implement this method and then come back if you are still having problems.
Please don't try to escape your parameters. Use bind variables. See http://bobby-tables.com/php.html for examples.