PHP script doesen't insert data in MySQL - php

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}')";

Related

Database doesn't get input

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.

Insert Muti Record From Android To Php?

When Send Data With Json From Android(AS) to Server (php+mysql) Must 1 Record Insert But Multi Record Selected Why?
my php code is:
include ('connect.php');
$jsondata = file_get_contents('php://input' );
if($jsondata==""){
echo "forbiden";
}
else{
$data = json_decode($jsondata, true);
//get the employee details
$user = $data['name'];
$namayandegi = $data['code_namayandegi'];
$code = $data['kala_code'];
$name = $data['kala_name'];
$tedad= $data['kala_tedad'];
$cost= $data['kala_cost'];
$date= $data['date'];
$confirm= $data['confirm'];
$email=$data['email'];
$sql="INSERT INTO `final_factor`(`id`, `name`, `code_namayandegi`, `kala_code`, `kala_name`, `kala_tedad`, `kala_mablagh`, `date`, `confirm`,`email`)
VALUES ('','$user','$namayandegi','$code','$name','$tedad','$cost','$date','$confirm','$email')";
if(mysql_query($sql,$con))
{
echo "1";
}
}
First of all you don't need to insert the id in you query and it's supposed to be AI.
So your query would be something like this
$sql="INSERT INTO `final_factor`( `name`, `code_namayandegi`, `kala_code`, `kala_name`, `kala_tedad`, `kala_mablagh`, `date`, `confirm`,`email`)
VALUES ('$user','$namayandegi','$code','$name','$tedad','$cost','$date','$confirm','$email')";
Second: The only reason why there are duplicate rows is that your code is repeating itself somewhere and for some reason. it could be multiple page loads or something like this. It's not possible to tell it because the code you provided has no errors so maybe it's not all the code. It would be great if you provide all your code. If you don't want look after what I told. Somewhere your code is called twice. Look after that.

SQL UPDATE not working

I am trying to update some of the data in a database called customer. This is my code
<?php
Require("dbconnect.php");
$Customer_id = $_POST['Customer_id'];
$Customer_title = $_POST['Customer_title'];
$Customer_forename = $_POST['Customer_forename'];
$Customer_surname = $_POST['Customer_surname'];
$Customer_contact = $_POST['Customer_contact'];
?>
all the variables are holding the correct data as I have test echoed them.
No errors are recieved when I run this code however it is not updating the database either? Can anyone help? Thank in advance!
String constants need single quotes (forename and surname):
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename = '".$Customer_forename."', Customer_surname = '".$Customer_surname."'
WHERE Customer_id = ".$Customer_id."";
Please note that your code may be susceptible to SQL injection.
There is one little thing that will quite possibly fix your problem. It is in the quotation.
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename='".$Customer_forename."',
Customer_surname='".$Customer_surname."'
WHERE Customer_id='".$Customer_id."'";

SQL syntax error edit post

getting :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

Categories