I have a php script, which contain a BLOB session image. I want to insert it into the BLOB column.
my wrong code
<?php
require 'config.php';
$userName = "John";
$aVatar = $_SESSION['userImage']; //[BLOB] - from MySql BLOB image
$query = "INSERT INTO `users`(`username`, `avatar`) VALUES ('$userName', '$aVatar')";
if($conn->query($query) == TRUE){
echo "Done!";
}
?>
When i post this, it show's very long strings into my page! and the message bellow all:
The problem here is that, if the variable $_SESSION['userImage'] contains any ', the query would not be valid. So you should use mysql_escape_string() to sanitize it:
$query = "INSERT INTO `users`(`username`, `avatar`) VALUES ('$userName', '" . mysql_escape_string($_SESSION['userImage']) . "')";
You can also use addslashes() while assigning the blob variable to solve this:
$aVatar = addslashes($_SESSION['userImage']);
Related
I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>
I have the following code that should collect the filled values from a former page and insert them in a MySQLi database. This does not work and I only get a blank page as a result, without any messages. I can't figure out what I'm doing wrong.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "INSERT INTO project VALUES('','$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<h1>Projektet är skapat!</h1><br>
Tryck på knappen nedan för att ta dig till Dashboard.<br><br>
<a href='dashboardadmin.php'><button id='projectbutton'>Dashboard</button></a>";
}
else
{
echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
}
?>
Correct syntax of INSERT is:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
Please try entering column names before your values first. Also check your $_POST values, whether $_FILES['image'] is available and confirm your mysqli connection.
Edits:
Is the first value (empty one) your primary key? If so, can you omit that bit in your code and try again? (Assuming pid is integer and auto incrementing value.)
INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')
Somehow I don't think this would be Azure specific issue as per your comment.
Can you see any errors in logs etc? Also try echoing the query before you run it and check if you run it directly on your phpmyadmin etc to see if it'd work.
Please also try using echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
at if($r){..} else { //here } to see if you get an error.
Latest Update:
$q = "INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('".$company_name."','".$description."','".$image."','".$image_type."','".$welcome_text."','".$thanks_message."')";
Try this, because your primary key value is auto incremented.
$q = "INSERT INTO project VALUES('$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";
I'm looking for a sql statement where I can add additoinal text to a form field when being submitted to a mysql database. For example: A field contains a file name that has been loaded to a Web server called "mydoc.pdf". I want to prepend the following text "http://www.example.com/uploads/", so when the form is submitted the field data becomes "http://www.example.com/uploads/mydoc.pdf".
Right now the unappended field "tofiles_link" uses the following mysql query statement to insert to the mysql database:
mysql_query("INSERT INTO site_tofiles (tofiles_title, tofiles_body,
tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip,
tofiles_post_user) VALUES
('".mysql_real_escape_string($_POST['tofiles_title'])."',
'".mysql_real_escape_string($_POST['tofiles_body'])."',
'".mysql_real_escape_string($_POST['tofiles_link'])."',
'".mysql_real_escape_string($_POST['tofiles_relation'])."',
'".mysql_real_escape_string($_POST['tofiles_type'])."',
'".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
'".mysql_real_escape_string($_GET['tofiles_post_user'])."')");
echo "Data was Entered Successfully!\n";
mysql_close($conn);
Can this be modified to suit my puroses? THX
To make the code more readable I would do your escaping before creating the SQL query. Not required but makes the code easier to read.
$title = mysql_real_escape_string($_POST['tofiles_title']);
$body = mysql_real_escape_string($_POST['tofiles_body']);
$link = "http://www.example.com/uploads/" . mysql_real_escape_string($_POST['tofiles_link']);
$relation = mysql_real_escape_string($_POST['tofiles_relation']);
$type = mysql_real_escape_string($_POST['tofiles_type']);
$ip = $_SERVER['REMOTE_ADDR'];
$post_user = mysql_real_escape_string($_GET['tofiles_post_user']);
Notice the $link variable on the 3rd line above adds the URL to the string.
$sql = "INSERT INTO site_tofiles (tofiles_title, tofiles_body, tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip, tofiles_post_user) VALUES ";
$sql .= "('$title', '$body', '$link', '$relation', '$type', '$ip', '$post_user');";
mysql_query($sql);
echo "Data was Entered Successfully!\n";
mysql_close($conn);
Ok I am having problems insert a variable into a sql table. Heres my code
if (isset ($_GET['comment']))
$commentEntered = $_GET['comment'];
else
$commentEntered = "refuse";
Above I get the variable
Then I try to pass it to the database with the code below
$sql = "insert into $DB_Table (comment) values('$commentEntered');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
My problem is, When I pass a single word it works, But when the text box where comment is received has any spaces in it, It will not insert?
i.e - The user enters Hello - This works
The user enters Hello World - This doesn't work
Any help would be much appreciated!
try
$sql = "INSERT INTO " . $table . " (comment) " .
"VALUES ('" . mysql_real_espace_string($commentEntered) . "')";
Also, dump the var $commentEntered before the "$sql = ..." line just to see what it outputs to the screen.
var_dump($commentEntered);
And another thing, try switching from GET request method to POST and grab the data from $_POST.
try to call:
mysql_query("COMMIT");
before closing the connection.
This code was designed to upload files from a flash javascript uploader plugin.
It doesn't give me an error but sometimes it does not insert the mysql query.
P.s: every posted variable is cleaned up via javascript (just alphanumeric text)
<?php
include 'a/inc/db.php';
if (!empty($_FILES))
{
$tempFile = $_FILES['Filedata']['tmp_name'];
if (substr($_FILES['Filedata']['name'],-3)!='mp3')
{
echo 'ERROR: your file was not an mp3';
die();
}
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_POST['folder'] . '/';
$titlepost = $_POST['title'];
$tagspost = $_POST['tag'];
$artist= $_POST['artist'];
$i= $_POST['i'];
$targetFile = str_replace('//','/',$targetPath) .time().".mp3";
$targetFilea = $targetFile;
$targetFilea = substr($targetFilea , strrpos($targetFilea , 'music') -1);
move_uploaded_file($tempFile,$targetFile);
mysql_query('set names utf8');
$sql = mysql_query("INSERT INTO `Music` (`filename`, `title`, `tags`, `rating`, `click`, `rand`, `album`, `i`, `artist`)
VALUES ('".$targetFilea."', '".$titlepost."', '".$tagspost."', '0', '1', '".$ras."', '1', '".$i."', '".$artist."');")
or die(mysql_error());
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', 'upload', '".$titlepost."');")
or die(mysql_error());
$click = mysql_query("SELECT *
FROM `Music`
WHERE `filename`='".$targetFilea."' ;");
while($row = mysql_fetch_array( $click ))
{
$mid=$row['id'];
echo "<id>".$row['id']."</id>";
}
mysql_close($connection);
}
echo "1";
?>
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', upload', '".$titlepost."');")
there is a ' missing before upload
try this instead (also added mysql_real_escape_string for security):
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".mysql_real_escape_string($i)."', 'upload', '".mysql_real_escape_string($titlepost)."');")
What really wrong is: your code is totally insecure. You sanitize POST-Data only using javascript and place it into your SQL query? Anybody can EASILY inject some custom SQL-Code and to really bad things to your database. Never ever rely on any HTTP-Data (be it GET, POST or anything else) to be secure.
I know you are new to PHP, so I honestly encourage you, for the sake of your customer, your project or anyone using your code, before you do anything else, sanitize your POST-Data with PHP before using it within SQL-Querys. Please.
There is even an article on Wikipedia on it, and it is a huge mistake newbies make with huge consequences which is quite easy to prevent.
http://en.wikipedia.org/wiki/SQL_injection
http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/ (Tip 1)
If the record is not getting inserted, this means most likely that there is some error. Possibly you have not set the proper error reporting that is why you don't see any error.
Put below two lines on top of your script so that all errors are shown.
ini_set('display_errors', true);
error_reporting(E_ALL);