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);
Related
I'm working on a school project involving a website with database integration. Currently working on adding new content (text, titles, images) to the website through it. I can already add new users to the database through the website, but for some reason the same code and logic doesn't apply for the content.
I noticed that printing $stmt with echo does not print anything.
<?php
include "../conn.php";
$sql = "INSERT INTO `contenido` (`id_contenido`, `tipo_contenido`, `id_seccion`, `orden_contenido`, `largo_contenido`, 'corto_contenido', 'extra_contenido') VALUES (NULL, '".$_POST["tipo"]."', '".$_GET['id']."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
$stmt = $conn->prepare($sql);
if ($stmt = $conn->prepare($sql))
{
//echo "It worked";
$stmt->execute();
$last_id = $conn->insert_id;
header("Location: editarContenidos.php?id=".$_GET['id']);
}
?>
Expected Results: The content information is uploaded to the database and the user is redirected to the Edit Contents page (editarContenidos.php)
Actual Results: White screen, no errors. Since the if condition is false, you are never redirected and the content is not uploaded to the database.
NOTE: The Insert User .php is working with the same logic and syntax, I'm not experienced enough with php to understand what I'm doing wrong.
I am assuming id_contenido is an auto_increment field and I'm not sure houw the backticks work in various languages. I would recommend adding some error handling PDO::errorInfo
and changing the SQL code to:
$sql = "INSERT INTO contenido (tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES ('".$_POST["tipo"]."', '".$_GET['id']."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
There is a $_GET['id'] in the SQL code and I cant tell if that is intentional.
I would recommend using parameters and some debugging using print_r($_POST);.
Try the following code:
<?php
include "../conn.php";
$sql = "INSERT INTO contenido (id_contenido, tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt))
{
//echo "It worked";
$stmt->execute(array($_POST["tipo"], $_GET['id'],$_POST["orden"],$_POST["largo"],$_POST["corto"],$_POST["extra"]));
$last_id = $conn->lastInsertId();
header("Location: editarContenidos.php?id=".$_GET['id']);
}
?>
I found out what the problem was. The quotation marks were not properly used.
The following code worked:
<?php
include "../conn.php";
$sectionid = $_GET['id'];
$sql = "INSERT INTO contenido (id_contenido, tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES (NULL, '".$_POST["tipo"]."', '".$sectionid."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
$stmt = $conn->prepare($sql);
//echo $sql;
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$last_id = $conn->insert_id;
header("Location: editarContenidos.php?id=".$sectionid);
}
?>
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']);
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 am validating my form using jquery and after the form is left with no errors, I want to insert the data into the database but for some reasons, it is not working properly. Can you help me find out my mistake. Thanks,
The JQuery is
$.post('register_user.php',
{
'name' : name,
'email' : email,
'password': password
},
function(data) {
if(data == "success"){
alert("success");
} else if(data == "fail"){
alert("fail");
}
});
THE PHP
$name = $_POST['name']; //else assign it a variabl
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT email FROM users WHERE LOWER(email) = '" . $email . "'";
$result = mysql_query($sql) or die("Could not get email: " . mysql_error());
if(mysql_num_rows($result) > 0) {
//email is already taken
}
else {
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')") or die(mysql_error());
$result2 = mysql_result($query);
if((mysql_affected_rows($result2) ==1){
echo 'success';
} else {
echo 'fail';
}
}
I dont have enough rep yet to comment, so I'll have to put this as an answer.
Step 1:
Echo (or print) out what you can.
Add echo inside your logic, like where you have: //email is already taken
Also echo out the POST variables.
If they all look OK, you should try to echo out your queries.
Eg. copy your query line that is like:
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')")
Then paste it and change it to:
echo "INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
Then if this looks bad, it's your query.. You can of course test the output in mysql directly via phpmyadmin or ssh to your server and run the commands through the console (if they give you shell access)
If you manage to get this to work, as some others commented: mysqli or pdo should be your next steps. You also need to do some basic stuff, even though that will take care of mysql injection.
You are still vunerable to XSS and also simply things like whitespace at the end of the email (users often get this, when they copy stuff and insert it into forms).
You can solve some of it by some helper functions you make in PHP, like:
function cleanData($data) {
return strip_tags(trim($data));
}
That was a very simple sample by me, you can also add other parameters to the function, like casing. Then you can switch the casing and do strtolower, strtoupper, ucwords(strtolower(, etc. And you can then simply wrap your variables inside the function :-)
Btw. E-Mail I would check with regular expressions. Also dont let JS / client side code do the input validation, as it's very easy to manipulate the DOM, or even post from an alternative source. You have to think of this data as "dirty", as it's easy to tamper with.
Here is my code
<?php
require("db.php");
$datetoday = date("Y-m-d");
if (isset($_POST['submit']))
{
include 'db.php';
$loginid =$_REQUEST['loginid'];
$result = mysql_query("SELECT * FROM info WHERE id = '$loginid'");
$test = mysql_fetch_array($result);
$testid=$test['id'];
$fnameloginsuccess1=$test['firstname'];
$mnameloginsuccess1=$test['middlename'];
$lnameloginsuccess1=$test['lastname'];
$departmentloginsuccess1=$test['department'];
echo'<input type="text" name="fname" value="<?php echo $fnameloginsuccess1 ?>"/></td>';
if (!$loginid)
{header("location:../index.php"); }
$natureofleave =$_POST['group1'];
$datestart=$_POST['startofleave'];
$dateend=$_POST['endofleave'];
$reason=$_POST['reason'];
$status= 'pending';
mysql_query("INSERT INTO `request`(id,natureofleave,dateofleavestart,dateofleaveend,reasons,datesubmitted,department,status,firstname,middlename,lastname)
VALUES('$log','$natureofleave','$datestart','$dateend','$reason','$datetoday','$departmentloginsuccess1','$status','$fnameloginsuccess1','$mnameloginsuccess1','$$lnameloginsuccess1')");
}
my main problem is i can't put the value of $fnameloginsuccess1, $mnameloginsuccess1','$lnameloginsuccess1',$departmentloginsuccess1 on my database..
but i can "ECHO" them.. some values are working but the 4 values didn't work!!
i already tried fname = $fnameloginsuccess1'; sadly to say it didn't work..
HELP!!
<?php
require("db.php");
$datetoday = date("Y-m-d");
if (isset($_POST['submit']))
{
include 'db.php';
$loginid =$_REQUEST['loginid'];
if (!$loginid) {header("location:../index.php"); }
$result = mysql_query("SELECT * FROM info WHERE id = '$loginid'");
$test = mysql_fetch_array($result);
$testid=$test['id'];
$fnameloginsuccess1=$test['firstname'];
$mnameloginsuccess1=$test['middlename'];
$lnameloginsuccess1=$test['lastname'];
$departmentloginsuccess1=$test['department'];
echo'<input type="text" name="fname" value="'.$fnameloginsuccess1.'"/></td>';
$natureofleave =$_POST['group1'];
$datestart=$_POST['startofleave'];
$dateend=$_POST['endofleave'];
$reason=$_POST['reason'];
$status= 'pending';
mysql_query("INSERT INTO `request` (id, natureofleave, dateofleavestart, dateofleaveend, reasons, datesubmitted,department,status,firstname,middlename,lastname) VALUES('$log','$natureofleave','$datestart','$dateend','$reason','$datetoday','$departmentloginsuccess1','$status','$fnameloginsuccess1','$mnameloginsuccess1','$lnameloginsuccess1')");
}
?>
Consider to use PDO statements as mysql_query is deprecated since PHP 5.5.0 and will be removed in the future.
http://www.php.net/manual/en/function.mysql-query.php
PDO connection examples
http://www.code.rusben.com/php-pdo-connection-with-utf8-compatibility-select-insert-update-delete/
<?php
require_once("db.php");
$datetoday = date("Y-m-d");
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$loginid = $_REQUEST['loginid'];
if (!$loginid)
{
header("Location: ../index.php");
exit;
}
$result = mysql_query("SELECT * FROM `info` WHERE `id` = '$loginid'");
$user = mysql_fetch_array($result);
$id = $user['id'];
$first = $user['firstname'];
$middle = $user['middlename'];
$last = $user['lastname'];
$dept = $user['department'];
$nature = $_POST['group1'];
$start = $_POST['startofleave'];
$end = $_POST['endofleave'];
$reason = $_POST['reason'];
$status = 'pending';
$sql = <<<SQL
INSERT INTO `request`
(`id`, `natureofleave`, `dateofleavestart`, `dateofleaveend`, `reasons`, `datesubmitted`, `department`, `status`, `firstname`, `middlename`, `lastname`)
VALUES
('$id', '$nature', '$start', '$end', '$reason', '$datetoday', '$department', '$status', '$first', '$middle', '$last');
SQL;
mysql_query($sql) or die ('There was an error processing your data.');
}
?>
A few points I feel the need to point out:
As you "require" the db.php, you should not need to "include" it.
When naming variables, it is best to keep them simple. Easier to debug and track down.
Exit the script after a header redirect. A delay in the header could allow further code to execute.
You can not use PHP tags inside of PHP tags - it just doesn't parse that way
I'd advise to write the SQL outside of the mysql_query() wrapper, since you can then echo out the SQL
Which can't be done if you write direct inside mysql_query()
log isn't defined, so it won't input. I'll assume that should be the users ID and edit to suit.
You had 2 dollar signs in the query (lnameloginsuccess1)
Anyway, if you run the above code and get "There was an error processing your data.", you can debug this pretty easily.
Change
mysql_query($sql) or die ('There was an error processing your data.');
to
mysql_query($sql) or die (mysql_error());
If the error it reports is vague, you tend to get better results running the query direct into the admin panel (PhpMyAdmin and the likes), so do;
On the line before the mysql query, simply add "echo $sql;" and run the page again. Copy the entire output of the query and run in your database admin panel.
If there is no error there, you need to be looking at connection issues - like errors in connection data