Insert a web page in mssql table - php

i want to insert a web page (text format) in a table
When i do my query, it gives me a mistake. But when i remove the webpage (in a string), it works.
The variable is the $comment one.
The row for message is text (not varchar(255))
$query_insert = "INSERT INTO [".$project."_spec].[IsMessage] (project, message, note) VALUES('".$project."', '".$comment."', '".$note."')";
mssql_query($query_insert) or die(mssql_get_last_message() . "[ " . $query_insert . " ]");
Is there a way to convert HTML in text?
Thanks

Your are building your SQL code dynamically by injecting variables with random contents into your query:
$query_insert = "INSERT INTO ... VALUES('".$project."', '".$comment."', '".$note."')";
^^^^^^^^ ^^^^^^^^ ^^^^^
This way, it won't take long until you build an invalid query inadvertently:
$project = "Foo";
$comment = "It isn't ready yet";
$note = "See John's notes";
$query_insert = "INSERT INTO ... VALUES('".$project."', '".$comment."', '".$note."')";
var_dump($query_insert);
// string(71) "INSERT INTO ... VALUES('Foo', 'It isn't ready yet', 'See John's notes')"
^ ^
Start string | | End string... oops
I haven't used the legacy MSSQL extension so I don't know how you're supposed to fix this (apparently, you cannot!) but there's a user comment that proposes a custom function. You should drop the stripslashes() call but the rest looks correct (without actually having tested it).
If you happen to use Windows and it's not too late for a change, the newer SQLSRV provides a better feature set.

Related

SQL + PHP Update query

I've been trying to update my data according to the user session (UserLogin) but it kept saying: Data type mismatch in criteria expression. The print_r is just for testing purposes.
Thanks in advance,
Z
function Employee1_BeforeShow(& $sender)
{
$Employee1_BeforeShow = true;
$Component = & $sender;
$Container = & CCGetParentContainer($sender);
global $Employee1; //Compatibility
$Page = CCGetParentPage($sender);
$db = $Page->Connections["PettyCashMDB"];
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = ". $_SESSION['UserLogin'];
$db->query($sql1);
print_r($_SESSION['UserLogin']);
$db->close();
Employee1_BeforeShow #67-67106FAD
return $Employee1_BeforeShow;
}
EDIT: I've tried #NanaPartykar 's method and by accident I've noticed that it does get the value from $_SESSION['UserLogin'], just that somehow the datatype is different.
EDIT: It displays the error Data type mismatch but both of them are string and returns string.
Instead of Employee.[EmpID], use Employee.EmpID
You need some quotes:
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = \'". $_SESSION['UserLogin'] . "\'";
Z - There are a bunch of built-in Codecharge functions to assist with getting values from querystring, sessions and controls.
eg: CCGetSession("UserLogin", "default");
http://docs.codecharge.com/studio50/html/index.html?http://docs.codecharge.com/studio50/html/Components/Functions/PHP/Overview.html
and executing SQL with some validating (from 'Execute Custom SQL' help topic):
$db = new clsDBConnection1();
$SQL = "INSERT INTO report (report_task_id,report_creator) ".
"VALUES (". $db->ToSQL(CCGetFromGet("task_id",0),ccsInteger) .",". $db->ToSQL(CCGetUserID(),ccsInteger) .")";
$db->query($SQL);
$db->close();
The $db->ToSQL (and CCToSQL) functions convert and add quotes for relevant data types (ccsText, ccsDate).
There are many examples in the Manual under 'Examples' and 'Programming Reference' for PHP (and ASP, .NET, etc)
http://support.codecharge.com/tutorials.asp
I strongly suggest looking at some of the examples, as Codecharge will handle a lot of the 'plumbing' and adding a lot of custom code will causing problems with the generation of code. In your example, you should add a 'Custom Code' action to the Record's 'Before Show' Event and add your code there. If you add code just anywhere, the entire section of code (eg: Before Show) will change colour and no longer be updated if you change something.
For example, if you manually edited the 'Update' function to change a default value, then no changes through the IDE/Properties will change the 'Update' function (such as adding a new field to the Record).
Finally got it to work, this is the code $sql1 = "UPDATE Employee SET LastActive = Date() WHERE EmpID = '$_SESSION[UserLogin]' "; Thanks to everyone that helped out.

Apostrophe causing problems with insert

Hi I am using php to insert some data into a MS Access Database, which works fine in most cases, the only time it doesnt work, as far as I can see is where there is an ' in the field, in this case its an address i.e. St John's Road.
This is the query statement I am using:
$sql = "insert into tempaddress (`id`, `StreetAddress`, `Place`, `PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."','$SearchTerm')"; CustomQuery($sql);
And this is the error I am getting http://prntscr.com/58jncv
I'm fairly sure it can only be the ' within the string text that is messing it up, how can i change?
Apostrophes breaks SQL strings. So you should add slashes before each apostrophe in your SQL strings manually or use PHP's built in function addslashes().
Example:
$sql = "INSERT INTO myTable (value) VALUES ('Text that shouldn't break')";
$sql = addslashes($sql); // outputs "INSERT INTO myTable (value) VALUES ('Text that shouldn\\'t break')"
Source : php.net/manual/en/function.addslashes.php
Thanks, in the end I went with str_replace("'", "", $string);
You are using ' ' quote with the php variable $SearchTerm and use a backslash before column name.
Change your query statement to this:
$sql = "insert into tempaddress (\`id\`, \`StreetAddress\`, \`Place\`, \`PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."',$SearchTerm)"; CustomQuery($sql);

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

PHP, trying to get $_POST['var'] into table as text

i'm having trouble with the code below. it's been simplified to show the problem. i use a loop because the input names are identical and need to create multiple new rows in a mysql table. the problem is i'm using $_POST['name'][$i] and the table won't accept because it doesn't see it as 'text?, ...i think.
like i said, code's been greatly simplified.
for($i=0;$i<count($_POST['url']); $i++) {
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
i tried to rememdy with this -
$sql = 'INSERT INTO urls (url) VALUES ('. '"'. $_POST['url'][$i].'"'. ')';
if i do this it works, there is no error
$sql = 'INSERT INTO urls (url) VALUES (' " hello " ')';
this is probably a newbie type mistake, right? thanks for any help with this.
A cleaner way (and the errors are fixed):
$urls = (isset($_POST['url']) && is_array($_POST['url'])) ? $_POST['url'] : array();
foreach($urls as $url) {
if(!is_string($url)) {
continue;
}
$sql = "INSERT INTO urls (url) VALUES ('" . mysql_real_escape_string($url) . "')";
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
Making sure the $_POST['url'] is an array will keep from trying to treat a non array (or non-existent key) as an array. The is_string is to protect from a user trying to throw in a sub array to get PHP to throw a "using array as string" notice. The escape is to avoid SQL injection, and the single quotes added are so MySQL knows it's a string.
You simply need to add quotes around the POSTed value in your MySQL query like below. Also, if you don't escape the input, it's a massive SQL injection vulnerability:
$data = mysql_escape_string($_POST['url'][$i]);
$sql = 'INSERT INTO urls (url) VALUES ("'.$data.'")';
The query breaks MySQL because MySQL thinks your post value is supposed to be numeric without the quotes.
It would be helpful to see that actual error message returned by mysql_error() but I think your problem is that you're not providing the $_POST value to the sql query as thought it's text.
try replacing
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
with
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i]) ."')";
You need to escape your $_POST variables before you insert them via an SQL statement, preferably using the mysql_real_escape_string() function to fortify your query against SQL injection attacks.
Answer provided by Corbin is good - however try not to fire insert queries in a loop.
You could create the sql query as one string and then fire the insert query once.
You could change your insert statement from
insert into table (field) values(1);
insert into table (field) values(1);
To:
insert into table (field) values(1), (2), (3), (4)...
This is a more optimal solution - however mysql has a max length to which it can take sql statements - therefore use your best judgement.
try this statement
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i])."')";

Categories