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)";
Related
I'm trying to execute following SQL query using YII frameowrk
Query= select * from table where name='Bachelor''s degree'
By executing the above query I'm getting empty results. But I have content in tables.
From my perspective I think Yii framework not accepts query with single quotes in its contents.
So could you please suggest some other idea to resolve this issue ?
Thanks in advance.
Try query with parameter.
$name = "Bachelor's degree";
Yii::app()->db->createCommand()
->select()
->from('table_name')
->where('name = :name', array(':name' => "{$name}"))
->queryAll();
In YII way, bind your value to the statement.
$name = "Bachelor's degree";
$command=Yii::app()->db->createCommand();
$command->select('table_column1,table_column2,table_column3');
$command->from('table');
$command->where('name=:name', array(':name'=>$name));
echo $command->queryAll();
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);
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.
I need to insert some data into mysql. I am not sure if I need to check the inputs OR format/strip them before they could be inserted into database fields as results returned from web may contain characters that mysql do not accept(I think). I have trouble with inserting tweets into mysql table. The type of field is varchar. This is insert statement in php script:
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status)
{
$t = $status->content;
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error());}
}
Yes, it's very important to escape all values before using them in an SQL command.
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status) {
$t = mysql_real_escape_string($status->content);
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if( !mysql_query($query, $dbh) ) {
die('error:' .mysql_error());
}
}
Also, other possible issues with your query:
If the id field is auto_increment'ing, you don't need it in the field or value list.
I may be missing something, but why are you using the string 'ID' for the msg_id field?
As for help troubleshooting this, I'd recommend just appending all of the $query strings to a log file for later inspection. Then, if problems aren't readily apparent, you can just manually try to run the command on the database (ie: maybe via PhpMyAdmin) and check out any error codes from there.