Database doesn't get input - php

I coded a function in PHP, which posts information of upload into a database table. If someone uploads a file, I will get the DateTime of the upload and his account number but I have an issue with the file name because the user is allowed to upload more than 1 file.
fdatum is Datetime
fmandantnr is User Number
fdateiname is Name of the file
The code is like following:
datensenden_copy.php
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
echo $query;
$omy->Query($query);
?>
I did my research and found out I need to get this:
for($i=0;$i<count($_FILES['userfiles']['name']);$i++){
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
Into this:
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
because the code cant get fdateiname in the SQL statement
Thank u for ur time.

You are looping over the $FILES array and getting the filename, but your INSERT command is OUTSIDE the loop so you only do ONE INSERT, with data from the last occurance in the loop. So simply move the insert inside the loop
In your code $fdatum does not appear to be defined anywhere, I hope/assume that was just left out of the sample code you gave us, or maybe it is created in the require.php code
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
$omy->Query($query);
}
?>
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
As I dont know anything about your clsMYSQL(); I cannot recode this to correctly use prepared statement.

Related

PHP script doesen't insert data in MySQL

I've created this script to insert some data from PHP to MySQL, but it doesen't work, and I don't know why.
if (isset($_SESSION['userSession'])!="") {
$session_created=1;
$session_query = "SELECT * FROM users WHERE user_id=".$_SESSION['userSession'];
$session_query_result = $DBcon->query($session_query);
$user_row=$session_query_result->fetch_array();
}
if(isset($_POST['create_post_button'])){
$post_name = $DBcon->real_escape_string(strip_tags($_POST['post_title']));
$post_content = $DBcon->real_escape_string(strip_tags($_POST['post_content']));
date_default_timezone_set('Europe/Athens');
$post_date=date("Y-m-d h:i:sa");
$post_categ_id = $DBcon->real_escape_string(strip_tags($_POST['post_category']));
$post_creator = $user_row['user_name'];
$pass_flag=0;
$error_msg_cp = "Posted!";
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('$post_name','$post_content','$post_date','
$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if($DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
echo $error_msg_cp;
}
Thank you!
Edit:
The result of this code is:
Even with ini_set('display_errors', 'stdout'); it doesen't display the error...
This is the structure of the posts table in MySQL:
Seems to have a newline in your integer field.
Change your query like this. Single quote around '$post_categ_id' has changed.
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name)
VALUES ('$post_name','$post_content','$post_date',
'$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if (!$DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
NB I suggest you to read this post How can I prevent SQL injection in PHP? to prevent your queries against SQL injections.
Change your insert query as follows, use '{$variable}' instead of '$variabe'
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('{$post_name}','{$post_content}','{$post_date}','
{$post_categ_id}','{$post_creator}')";

Seemingly identical sql queries in php, but one inserts an extra row

I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.

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.

Can not use POST variable in PHP insert query

In my PHP file I do the following
<?php
if(isset($_POST['submit'])){
$con = mysqli_connect(bla);
$query = "insert into users (name,username,password) values($_POST['name'],$_POST['username'],$_POST['password'])";
}
Now, even if if condition is not satisfied, that is when submit is not done, I get error. But when I comment my $query = ... line, there is no error. What is happening?
You need to put '". around your variables, like this:
$query = "insert into users (name,username,password) values('".$_POST['name']."','".$_POST['username']."','".$_POST['password']."')";
place any $_POST['...'] between {}
Like '{$_POST['password']}','...
put this code At the end for display Errors:
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
When you interpolate an array variable into a string, there are two ways to write it: either put curly braces around the variable, or leave out the quotes in the index:
$query = "insert into users (name,username,password)
values('{$_POST['name']}', {'$_POST['username']}', {'$_POST['password']'})";
You also need quotes in the query itself, for correct SQL syntax.
Consider putting your post values into local variables first and then enter the local variables as the values of the insert query. ex:
$name = $_POST['name'];
$query= INSERT INTO users(name)VALUES("$name")

Categories