i have three options for a photo or video being uploaded to the site , i have this select option to pick what the file is being uploaded sorta like a tag. its not placing it in the database. here is my code:
Here is where i call on it
$type1 = $_POST['type'];
$type = mysql_real_escape_string($type);
$sql = mysql_query("INSERT INTO photos
SET photo='$newname', title='$title', date='$date', author='$by' , type='$type'")
Here is where it is made
<select name="type" id="type">
<option value="Pic">Picture</option>
<option value="Video">Video</option>
<option value="Gif">Animated picture (GIF)</option>
</select>
use this INSERT syntax
INSERT INTO photos (photo, title, date, author, type )
VALUES ('$newname', '$title', '$date','$by' , '$type')
As a sidenote, the query is vulnerable with SQL Injection. Please read the article below how to prevent from it,
How to prevent SQL injection in PHP?
The code you posted is the real code? It looks like when you're escaping, you're not using the actual data from the Select.
$type = mysql_real_escape_string($type); // You are escaping the $type variable, which is NULL, it was just declared
But you're reading the data from the Select using this variable name
$type1 = $_POST['type'];
So you're using $type1 somewhere, and $type somewhere else.
Related
Using PHP Version 7.1.9, MariaDB 10.1.26.
I'm submitting form data to a MySQL database, one of my values is NULL however in the database it's empty.
I have ensured that my database table is set to;
allow null = yes
default - null
My code is below (please ignore any security vulnerabilities this is simplified code);
$id = $_POST['id '];
$name = $_POST['name'] ? $_POST['name'] : NULL ;
$sql = "INSERT INTO staff (id, name) VALUES ('".$id."', '".$name."')
// query runs and inserts successfully
When I var_dump($name) I get NULL, although the name value in my database is empty (i.e. not null)
Any ideas what i'm doing wrong?
Edit
The original poster said
My code is below (please ignore any security vulnerabilities this is simplified code)
I interpret that as "I know about SQL injection and I am taking measures to prevent it in my code. I've simplified my post to make it easier to get an answer."
My response below is following their format. That's why I did not use PDO, mysqli, prepared statements/escape measures in my post. If I were personally writing code to insert data into a database, I would make sure my data is sanitized and I would use an ORM like Doctrine (which is a wrapper for PDO) to interact directly with the database.
My Answer
Referencing the code in the original post:
$id = $_POST['id '];
$name = $_POST['name'] ? $_POST['name'] : NULL ;
$sql = "INSERT INTO staff (id, name) VALUES ('".$id."', '".$name."')
// query runs and inserts successfully
Your query is behaving the way you've written your code. If you echo/print a PHP variable to standard output after it has been set to NULL you won't see a value at all. Null is the absence of value. Since you've wrapped the absence of value (no value, null) in single quotes, you're telling MySQL that you want to insert an empty string into the name column.
I would rewrite the code as follows:
$id = $_POST['id '];
$name = $_POST['name'] ? "'$_POST[name]'" : 'NULL';
$sql = "INSERT INTO staff (id, name) VALUES ('$id', $name)";
Notice how I put NULL in a string for the name variable. When I include the name variable in the query I don't wrap it with quotes. This is the proper way to explicitly add a null value to a column in MySQL.
PHP's double quotes allows variable interpolation. This means you don't have to break your strings down into individual parts and concatenate string values together. This makes the code cleaner and easier to read.
First, you're obviously not using prepared statements. I strongly advice you to use prepared statements in the name of security and stability.
Then, on to the issue at hand. The database doesn't know what a PHP null is and will only see an empty string to be inserted in your code.
"" . null . "" === ""
Keeping your (very dangerous and vulnerable) example code, and modifing the place where you add the "quotes" around the to be inserted string. If the name is null just insert NULL without quotes around it. the databse server will interpret that as having to inserta null value
$name = $_POST['name'] ? "'".$_POST['name']."'" : 'NULL';
$sql = "INSERT INTO staff (id, name) VALUES ('".$id."', ".$name.")";
Now really, investigate how to do prepared queries to prevent SQL injections
or at least use mysqli_real_escape_string or something equivalent.
this is the more secure version, using PDO.
$sql = "INSERT INTO staff (id,name) VALUES (:id,:name)";
$stmt= $dpo->prepare($sql);
$stmnt->bindParam(':id', $id, PDO::PARAM_INT);
if(!$POST['name']) {
$stmnt->bindParam(':name', null, PDO::PARAM_NULL);
}
else {
$stmnt->bindParam(':name', $POST['name'], PDO::PARAM_STR);
}
$stmt->execute();
I would instead use PDO prepared statements. That should set the value to NULL instead of an empty string. Because you are wrapping '".$name"' it is making the query '') - i.e an empty string.
I'd do like this:
$id = $_POST['id '];
if(isset($_POST['name'])){
$sql = "INSERT INTO staff (id, name) VALUES ('".$id."', '".$name."')
}else{
$sql = "INSERT INTO staff (id) VALUES ('".$id."')
}
discriminating the query if I receive the name from the form or not.
You should use prepared statements to pass variables (user inputs) to a mysql query. Otherwise you are widely open to SQL injections.
Alright so I have two tables that I am working with.
The first is set up something like these tables
Destination
IDDestination Name IDCity IDState
1 Scottsdale 3 4
2 Miami 5 7
and
Destinations_Citites
IDDestinationCity IDDestination IDCity
1 1 3
2 2 5
Now with my plugin I have an add a new destination button which adds a new destination with its Name, IDCity and IDState filled out by the user and the IDDestination is automatically generated.
So what I want to figure out how to do is to grab that automatically generated IDDestination # and enter it into the Destinations_Cities table with out having the user do anything else.
Basically how can I insert the automatically generated IDDEstination that was just created and throw it into my other table without the user having to add it themselves.
Here is the code I am using to Insert and Update for my add destinations button
if(isset($_POST['Add_Destination'])) {
$idstate = $_POST['idstate1'];
$idcity = $_POST['idcity'];
$name = $_POST['addname'];
$SQL="INSERT INTO destination (name, IDCity, IDState) VALUES ('". $name ."','". $idcity ."','". $idstate ."')";
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
$result=mysql_query($SQL) or die (mysql_error());
$result1=mysql_query($SQL1) or die (mysql_error());
print $SQL;
print $SQL1;
}
You can get the most recent auto-increment id generated during your session:
$dest_id = mysql_insert_id();
Refer to the documentation: http://php.net/manual/en/function.mysql-insert-id.php
Not exactly about your question, but I echo the comment above that you should protect your queries from SQL injection vulnerabilities. Don't copy PHP variables into SQL strings unless you have made sure the variables are made safe.
If a variable is supposed to be an integer, use (int) to cast it to an integer as you read it.
For string values, use escaping provided by the MySQL API.
Also, there's no need to do all the . concatenation if you're just putting simple variables inside PHP strings. There's no need in SQL to put quotes around integer literals.
Here's an example:
if(isset($_POST['Add_Destination'])) {
$idstate = (int) $_POST['idstate1'];
$idcity = (int) $_POST['idcity'];
$name = mysql_real_escape_string($_POST['addname']);
$SQL="INSERT INTO destination (name, IDCity, IDState)
VALUES ('$name', $idcity, $idstate)";
$dest_id = mysql_insert_id();
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
. . .
If you convert your code to use PDO, you can use SQL query parameters, in which case you wouldn't need to worry about escaping and such.
I am getting an error on attempting to insert/update single field with multiple entries.
Here is database scheme:
id INT(8) NOT NULL auto_increment,
name VARCHAR(64),
hobby VARCHAR(500)
HostServer Php version is 5
Here is what my form code is :-
<form method=post>
<label>name</label>
<input type=text name=name>
<label>hobby</label>
<select name="hobby[]" multiple="multiple">
<option value=1>gardening
<option value=2>Music
<option value=3>Movies
<option value=4>Games
</select>
</form>
Now for processing the multiple values am using following php code :-
foreach($_POST['hobby'] as $key => $value){
$_POST['hobby'][$key] = mysql_real_escape_string($value);}
$hobby = $_POST['hobby'];
$hobby = "('" . implode("'),('" , $hobby). "')";
$sql = mysql_query("UPDATE `users` SET name='".$name."',hobby='".$hobby."'");
But am getting the following error on output :-
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 '2'),('3')' on line....
I know this is the entries related to hobby field but am unable to find an way to
correct it. Any help will be appreciated.
try to help your self
change this line
$sql = mysql_query("UPDATE `users` SET name='".$name."',hobby='".$hobby."'");
for debugging into
$query = "UPDATE `users` SET name='".$name."',hobby='".$hobby."'";
echo $query;
die;
after this you can see that your query isn't valid. check out the error and fix your implode
The Database schema looks a little strange but the only reason this isn't working is you need to escape the single quotes that you want to be entered into the database. This is done with a preceding '\'
$hobby = "(\'" . implode("\'),(\'" , $hobby). "\')";
There are other issues to consider though, for one this statement will update every record in the database because you haven't specified a where clause.
you also are not passing the content of the name field to to the SQL statement. you should chnage:
$name to $_POST['name']
is there anyway to get the ID of the current record I am INSERTING into the database table using php with Mysql without having to do an extra select to get the last ID?
FOr example, if my table has these columns, id, url, name
and if url consists of the domain name and current id as the query variable ex:
domainname.com/page.php?id=current_id
$sql="INSERT INTO Persons (id, url, name )
VALUES
('domainname.com/page.php?id=".**whats_the_current_id**."','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
as far as I know, there is no 'clean' way to find the ID you are about to insert (from what I understand from your question, this is what you want to know).
Two options in my opinion, starting with the ugly one: select max(id) from Persons, increment it with one, and hope that no insert's will mess this up for you. Like I said, its ugly, and -not- reliable.
A better option would be to first insert the record with a dummy value for url, and then retrieving the just inserted row's ID with mysql_insert_id(). Then update that record with the correct url value.
You asked for a way to retrieve the id without a select query following the insert query, but like I said, I don't think this is possible.
i use mysql_insert_id() for that. it works fine.
// pseudo-ish code
$query = "INSERT something .... "
$updated = $db->run_query($query);
$id = mysql_insert_id();
your table should be like this
ID AUTO_INCREMENT
person_id VARCHAR
person_url ...
person_name ...
your post form something like
<form method="post">
<input type="hidden" name="id" value="<?php echo uniqid() ?>" />
...
</form>
the query should be like this:
$person_id = intval($_POST['id']);
$person_url = mysql_real_escape_string($_POST['url']);
$person_name = mysql_real_escape_string($_POST['name']);
mysql_query("INSERT INTO Persons (person_id, persno_url, person_name) VALUES ( {$person_id} , {$person_url}, {$person_name} )");
$ID = mysql_insert_id();
The current ID is in $_GET['id']. You should sanitize it before inserting it into your query:
$id = intval($_GET['id']);
Then, use $id in your query.
If you add classes around the first insert and then the second select. The select will work then.
<?php
class insert1{
function inserthere(){
***insert***
}
}
class select1{
function selecthere(){
***select***
}
}
$a = new insert1;
$a->inserthere();
$b = new select1;
$b->selecthere();
?>
my sql insert query is not working in my program. I have print the query and then copy paste that code in mysql tab of the phpmyadmin, then it works perfectly. Any body please help me.
if ($_FILES["thumbnailimage"]["size"]>0 )
{
$thumbnailkey = generateUniqueKey($tbl_uploads,"upload_key",12);
$fkey = generateUniqueKey($tbl_uploads,"file_key",24);
$folderkey = generateUniqueKey($tbl_uploads,"folderkey",28);
$fname = substr($_FILES['thumbnailimage']['name'],0,strpos($_FILES['thumbnailimage']['name'],"."));
$ext = getExtension($_FILES['thumbnailimage']['name']);
$insertnewupload = "INSERT INTO ".$tbl_uploads." (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."','".$_SESSION['user_id']."','0','".$productkey."')";
echo "<br>1=>".$insertnewupload;
// $db->connect();
$exec_insertnewitem = mysql_query($insertnewupload);
This is the printed out put
INSERT INTO tbl_uploads (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')
You are quoting numeric values, you should aim for. I've added backticks around the field names also (I can't recall if 'status' is reserved)
INSERT INTO `tbl_uploads` (
`upload_key`,
`file_key`,
`file_name`,
`file_type`,
`ext`,
`folderkey`,
`user_id`,
`status`,
`pkey`
)
VALUES (
'f958c38e5c31',
'9b6bd5118ec4a8456bcc46df',
'sunil',
'1',
'jpg',
'1c1a536fbdde4f24a219ada4c1c9',
7,
0,
'3b593aff92ce'
)
So the following replacement for the line specifying values will suffice
$insertnewupload = "INSERT INTO `".$tbl_uploads."` (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status`,`pkey`) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."',".$_SESSION['user_id'].",0,'".$productkey."')";
As an addition, there'll probably be a few comments stating you should be using mysqli_ functions or PDO instead of mysql_. At present you're potentially vulnerable to SQL injection with such a method of making a query.
Could be severy reasons... did you check that you connect to the correct database ? Maybe add the database name before "tbl_uploads", e.g. "mybase.tbl_uploads"
Always make practice to write mysql query like this.
$query = "INSERT INTO tablename (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status,pkey`) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')";
$check = mysql_query($query);
check if var_dump($check);returns true or false..