storing source efficiently into sql escaping - php

Im having issues with storing source code into a db for a small script bin. The issue is that the printed code in the syntax highlighter used to view from the db has line breaks where it shouldnt, i have seen also in the db the text has stored in the same manner.
I have tried using severalk means to make this work, at first i thought was a wrap issue, so i set wrap to hard on the input form. Then added addslashes and that did not work, ive tried magic_quotes and in this case shown below ive tried mysql_real_escape_string and the text that comes from $content will store in the db with line breaks in places they shouldnt be.
Am i missing something? thanks
This code below is the insert into db and the value concerned is $content
<?php
session_start();
$submit = $_POST['submit'];
$sniptitle = ($_POST['sniptitle']);
$date = date("Y-m-d H:i:s");
$user = $_SESSION['username'];
$lang = ($_POST['lang']);
$con=mysqli_connect("localhost","xxxx","xxxx","xxxx");
$content = mysql_real_escape_string($_POST['snipcontent']);
// ^^^HERE IS THE ISSUE ^^^
if(isset($_POST['submit'])) {
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO code_lib ( snip_title , snip_content , posted_by , lang , datetime )
VALUES ('$sniptitle' , '$content' , '$user' , '$lang' , '$date' )");
mysqli_close($con);
header ("Location: xxx"); // Move back to a page
exit();
}
?>

mysql_real_escape_string shouldn't be used with mysqli by any means
thevertheless, it shouldn't be an issue either
most likely your "solution" is paired with stripslashes on fetch
So, the right solution would be
turning magic quotes off
and using mysqli_real_escape_string

Related

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

Trying to mysqli_query to INSERT INTO my database. Not receiving errors

I'm trying to make a very basic form that inserts into my database. I've worked through countless hours working on this. I feel I understand each line of code. I can't imagine what the problem is. I'm not receiving any errors, although I haven't set up error checks in my code yet. Hopefully my problem is simple and obvious.
Here is my connect.php file. $con is my connection to a new mysqli. talk is my database.
<?php
$con= new mysqli("localhost","root","","talk");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here is the relevant form part of my html. title and content and the two pieces of information I'm trying to insert into my database. I include the connect.php. The textarea should be linked to the form through the form="talkform". This form uses action="process.php", which I'll cover next.
<?php
include 'connect.php';
?>
<center>
<h1>/talk/</h1>
<form method="post" action="process.php" id="talkform">
<input type="text" name="title"/><br><br>
<textarea form="talkform" rows="10" cols="80" name="content"></textarea><br>
<input type="submit" value="talk" />
</form>
And here is my process.php. I included connect.php in this file as well. Not sure if that's redundant and causing problems, but I don't think so. I also used this $_SERVER['REQUEST_METHOD'] bit you see, which I picked up from a tutorial. Not sure if there's a better way of accomplishing that. I put everything into variables. When I was working through errors, it was all on the mysqli_query line. I have the strongest suspicion that's the culprit.
<?php
include 'connect.php';
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
$title = $_POST['title'];
$content = $_POST['content'];
$operation = "INSERT INTO
main(title, content)
VALUES($title, $content);";
$result = mysqli_query($con, $operation);
}
?>
I hope that I didn't leave anything out. I've been struggling with getting a database working for over a week. It's been a painful process, and although I'm learning a lot, I'm not getting anything to work. Please help, and thank you.
use == operator to compare
if($_SERVER['REQUEST_METHOD'] == 'POST')
and quote your query variable
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
so code looks like with escape string
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = mysqli_real_escape_string($_POST['title']);
$content = mysqli_real_escape_string($_POST['content']);
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
$result = mysqli_query($con, $operation);
}
Also better to use check for post values exist or not with empty() or isset()
Line 4: if($_SERVER['REQUEST_METHOD'] == 'POST')
Better is check out directly if form was sent using if (isset($_POST['title'])).
When you call mysqli_error() you´ll find our you try to insert strings without quotes (and you don´t escape inputs - look for SQl injection).
$operation = "INSERT INTO main(title, content) VALUES('" . mysqli_real_escape_string($con, $title) . "', '" . mysqli_real_escape_string($con, $content) . "')";
You're not checking for errors after your mysqli_query call, of course you won't see any.
You're vulnerable to SQL injection. Use mysqli's prepared query syntax to avoid that. See How can I prevent SQL injection in PHP?.
Your immediate problem is that your query reads ... VALUES(foobar, baz), which is invalid. You're missing quotes around the values. However, if you properly use prepared statements, that will become a non-issue, so ignore that.

MySql update statement in PHP

I'm struggling with an update statement using php. The problem occurs when the string in the variable $fltr contains more than one word.
$fltr ="Two Words or More" does not work
$fltr="OneWordOnly" works fine.
require_once('includes/init.php');
$Login = new Login( $db );
if(empty($_SESSION['logged']))
{
$Login->_logout();
}
if(isset($_SESSION['uid']))
{
$userid=(int)$_SESSION['uid'];
}
$fltr = $_GET['filter'];
$fltr= pg_escape_string($fltr);
$deakt="D";
$updSQL="update class_products set FTP ='".$deakt."' where title ='".$fltr."' and owner =".$userid;
$db->query($updSQL) or die ("Error in query: $updSQL " . mysql_error());
$txt='<textarea style="margin-left:250px;margin-top:110px; font-family:verdana:font-size:14px;color:#000;">Search filter {$fltr} is deactivated</textarea>';
$class_tpl->assign('txt', $txt);
//now display the template
$class_tpl->display('cbUpdate.tpl.php');
Normally I would print the $updSQL to see the what the problem is, but I am using this in a LightBox variant and having problems debugging.
Any help is highly appreciated.
My guess is the value is urlencoded, and you need to urldecode it, before escaping.

I am trying to store form information in a mysql database but it does not foward to the database

So I have a form and the form action= the file that contains the code below. I am getting a connection but the data is not saving. I formatted my form with input type textarea and the database with long text because I want to give the user as much space as they need to write their information. I think this might be my issue and have been searching the web to see if it is but I can't find anything that says it is or not. The weird part is that one time i did see an increase in the row of the database but when I checked it the row didn't contain the info I sent, it was blank.
<?php
session_start();
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ='0')
{header('location:shareerror.php');}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
header ('location:thanks.php'); }
?>
By mistake you are assigning instead of checking corrected statement is:
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ==0)
There is an error in your query
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
change this to
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
You are not setting the values for $recipe, $usrtext and $usrtxt
You are missing a comma in the values.
You are using strlen instead of isset
Also please take a look at How can I prevent SQL injection in PHP?. Your code is vulnerable to sql injection.
Here is the fixed code (with sql injection vulnerability intact!!)
<?php
session_start();
if (!isset($_POST['recipe'])|| !isset($_POST['usrtext'])||!isset($_POST['usrtxt']))
{
header('location:shareerror.php');
}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$usrtxt = $_POST['usrtxt'];
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext','$usrtxt')");
header('location:thanks.php');
}
?>
Also you didn't assign the variables used in the query.
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
do that like this:
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$urstxt = $_POST['usertxt'];
Then you can use the variables in the query

Inserting data into two separate tables using PHP

I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ($desc_query) it won't update any table.
Here is my code:
$name= strip_tags($_POST['name']);
$l_name= strip_tags($_POST['last_name']);
$c_id = strip_tags($_POST['company_id']);
$a_d = strip_tags($_POST['add_description']);
$d_t = strip_tags($_POST['desc_text']);
$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!");
mysql_select_db('database_db') or die('could not connect to database!');
//inserting names
$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");
//inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
$desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}
You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks).
I would recommend sanitizing all user provided data like so:
$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);
Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL.
Have you tried to echo out the queries and then to run them directly on the database?
Without any more information about the database we can't really tell if the queries themselves are valid.

Categories