I have php script containing following SQL query (working oK):
$query = 'INSERT INTO persons'.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
Where $_REQUEST["name"] and $_REQUEST["name"] are variables passed from html form.
usin php 4.5 and MariaDB 5.5
Problem rises when i try to substitute persons by variable - eg. $table:
$table = "persons";
$query = 'INSERT INTO '.$table.''.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
I have been trying different variations with double qutes/single qutes/dots :). But still struggling with this..
Thx for possible answer.
Its a simply case of knowing how the single and double quote works in PHP
Try this
$table = 'persons';
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
Now of course you should not be using the mysql_* extension anymore but if you have to you should at least try and sanitize the input values before you use them
So the code becomes
// do at least this to sanitize the inputs
$_REQUEST['name'] = mysql_real_escape_string($_REQUEST['name']);
$_REQUEST['surname'] = mysql_real_escape_string($_REQUEST['surname']);
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
$table_name = 'persons';
$query = "insert into ".$table_name." (name,surname) values ('".$_REQUEST['name']."','".$_REQUEST['surname']."') ";
Related
I have problem my code not working
I need to write 5 columns
can you explain how to can I use this code right
$val="('".implode("'), ('",$student)."')";
$sql = "INSERT INTO `tbl_student`
(`student_name`) VALUES ".$val.";";
I think this is what you're trying to do:
$val = "('".implode("','", $student)."')";
$keys = "(".implode(",", array_keys($student)).")";
$sql = "INSERT INTO tbl_student ".$keys." VALUES ".$val.";";
Warning: you should make sure your code is not subject to mysql injection. Values coming from the $student array should be sanitized if they comes from user input.
Hi im trying to hard code and set a date to a variable inorder to insert it in db table, but after all my efforts it always prints 0000-00-00 00:00:00. data type in the date column of the table is just datetime
following is the code i tried
$retval = '2007-04-19 12:50:00';
$str_cols = "gmid, panelID, trackerID, timestamp";
$str_values ="$gmid, $panel_id, $track, $retval";
$table = "tracktable_".$track;
$query = "INSERT INTO $table ($str_cols) VALUES ($str_values)";
can any body help on this to get the assigned date in the db table
timestamp is a keyword so it should be in apostrophe like 'timestamp'.
$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp') VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";
For it to function surely. Add backticks to your $table. Also there is no single quotes in your values. Use this for sure it will work.
$query = "INSERT INTO `$table` (gmid, panelID, trackerID, timestamp) VALUES ('$gmid', '$panel_id', '$track', '$retval')";
$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp`) VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";
Try
$str_cols = "gmid, panelID, trackerID, `timestamp`";
$str_values ="$gmid, $panel_id, $track, '$retval'";
I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));
I am facing some problem with fetching data from SQL.
When I use the below statement, it is working fine
$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'facebook\'';
$retval = mysql_query( $sql, $conn );
When I use the same using a parameter name, I am facing some problem, the code I used is
$name = $_GET['name'];
$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'$name'';
$retval = mysql_query( $sql, $conn );
I also tried by concatenating name like \'facebook\'
$name1 = "\'".$name . " \'"; but it is also not working .
use Double quotes so you won't need any escaping of single quotes.
$sql = "SELECT Name, Des, Url, about, date
FROM data
where name = '$name'";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Use Mysqli instead of Mysql.
Solution for your query :
$name = $_GET['name'];
$sql = "SELECT Name, Des, Url, about, date FROM data where name = '".mysql_real_escape_string($name)."'";
$retval = mysql_query( $sql, $conn );
It must be the simplest error, but I dont see nor find it.
I fill a variable $aa_minerid with value 7.
I use this variable in a insert.
The insert always inserts a 0 (zero) in the database never a 7
The field i put it in is a smallint(6)
I tried
VALUES ('$aa_productid')
VALUES ($aa_productid)
VALUES ("$aa_productid")
VALUES ('{$aa_productid}')
VALUES ("{$aa_productid}")
and all with use of ` aswell
into script placed hereafter.
If I put there : VALUES ( 7 )
It does work perfect.
So what do I do wrong in this script?
BTW the echo at the end DOES show the right value of the variable $aa_productid
<?php
/* This php script should transfer data from the aa to the sql database */
// Info coming from aa
$aa_productid = 7 ;
include ("dogs.inc");
$cxn=mysqli_connect($host,$user,$passwd,$dbname);
$query = 'SELECT * FROM `Price` WHERE '
. ' `Time_Stamp`=(select max(`Time_Stamp`) from `Price` where `Product_ID` = \'1\')';
$result=mysqli_query($cxn,$query) or
die("Couldn't execute select query");
$row = mysqli_fetch_row($result);
$aa_price=$row[3] ;
$aa_value = $aa_price * $aa_amount;
// Info ready to go to database
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ( $aa_productid )' ;
echo $aa_productid;
Single quotes don't do variable expansion in PHP. But I would recommend you use prepared statements, such as:
$stmt = $cxn->prepare('INSERT INTO Mining (Product_ID) VALUES ( ? )');
$stmt->bind_param('i', $aa_productid);
$stmt->execute();
See the documentation at prepare and bind_param.
This will protect you from SQL injection.
Try
'.$aa_productid.'
or
".$aa_productid."
Depending on the type of apostrophe used to beging the string, use the same one.
Also, if You are using ", then You should be able to Just do
$insert="INSERT INTO $tablename;";
It's been a while since I have done any PHP but..
I think you need to have smartquotes turned on
Try this instead:
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ('. $aa_productid .' )' ;
concatenate the variable into the query.
When you are using variables within quotes, you must use the double-quote if you want PHP to parse variables within it. So, this would work:
$sqlinsert = 'INSERT INTO Mining (Product_ID) VALUES ('.$aa_productid.')';
Or this would:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ($aa_productid)";
Try:
$query = "SELECT * FROM Price WHERE Time_Stamp=(select max(Time_Stamp) from Price where Product_ID = "1")";
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ( '$aa_productid' )" ;
Also, its always a good idea to escape the strings before entering them in the db.
Try this syntax instead:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ("' . $aa_productid . '")";
no need to concatenate the two parts of the insert. Also double quoting the variable seems to avoid problems.