I have the following line of code that executes properly except for one hitch. It will print the variable name into the database.
I use this code in one of my scrips:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, \'$first_name\', \'lname\', \'addr\', \'\', \'city\', \'state\', \'zip\', \'ordernum\', \'\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\');";
mysql_query("$sql");
mysql_close($con);
This code prints the followin to the database:
$first_name lname addr city state zip 0 0 0 0 0 0 0 0 0 0 0
Notice that the variable name, and not the contents of the variable are printed. How can I get it to print out the variable contents?
Notice that the variable name, and not the contents of the variable are printed
This is because you are not passing variables to the insert statement, rather you are passing undefined(?) constants; lname, addr, etc. You should pass in the variables you assigned values to: (assuming) $lname, $addr, etc.
Also, you don't need to pass in a NULL for the ID column. If it's set to auto_increment, the database will create this value for you.
You should also take advantage of the default column values defined by your table schema, so you don't end up passing in a huge list of variables with default values, for example, if you have a DEFAULT 0 as part of the schema for item1, item2, item3 etc, you can simply make the following insert:
$sql =
"INSERT INTO `MyDB`.`Shipping` (`FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`) VALUES ('$first_name', '$lname', '$addr', '$city', '$state', '$zip', '$ordernum');";
The database will populate item1, item2, etc columns with 0 for you automatically.
As cambraca mentioned, if you pass variables directly into your query like this, you run the risk of SQL injection. You should read up on how to prepare your queries, which will also force you to use mysqli (vs outdated mysql) api. Or even better, read up on PDO.
For one you have a quoting issue. You seem to have double quotes and then escaped single quotes. don't escape your single quotes if you string is double quoted.
It seems the value of $first_name should work. Is this the exact code? Because if you have single quotes around the whole thing it would create the output you're describing.
All your other columns aren't variables so it's hard to know what you're trying to do. If you aren't going to use them why reference them at all?
In your mysql_query call don't quote $sql again.
Finally check mysql_error() for errors. It could be you are seeing something old in the database and your code isn't working at all.
Consider using PDO. It has support for placeholders, better security and better debugging than the native mysql_* interface.
Change the insertion statement to:
$sql = "INSERT INTO `MyDB`.`Shipping`
(`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`,
`STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`,
`item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`)
VALUES (NULL, '{$first_name}', 'lname', 'addr', '', 'city', 'state',
'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0');";
Also, do check that your $first_name is properly assigned a value.
I suppose not to use inline variables in strings in PHP, and you are escaping ' when you do not need to. Try this:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, '".$first_name."', 'lname', 'addr', '', 'city', 'state', 'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');";
mysql_query($sql);
mysql_close($con);
Rather than using \'$first_name\' replace it with \"$first_name\" and the same follows with other variables too.
Related
$logquery="INSERT INTO new_data_entry_log (directory,ip,description,state,status,instituteid,email,category,bandwidth,project,institutehead,contactnumber,landlinenumber,latitude,longitude,clientip,added by,added on,added at) VALUES ('$directory','$ipaddress','$description','$state','$status','$instituteid','$contactemail','$bandwidth','$institutehead','$contactNumber','$contactlandlinenumber','$latitude','$longitude','$clientip','$name','$currentdate','$currenttime')";
I can see there is a mismatch of columns count and related values count. Probably it might be the issue.
Did you try with removing the single quates of the variables?
I have formated your query.
Formated Query
$logquery="INSERT INTO `new_data_entry_log`(
`directory`,
`ip`,
`description`,
`state`,
`status`,
`instituteid`,
`email`,
`category`,
`bandwidth`,
`project`,
`institutehead`,
`contactnumber`,
`landlinenumber`,
`latitude`,
`longitude`,
`clientip`,
`added by`,
`added on`,
`added at`
) VALUES(
'$directory',
'$ipaddress',
'$description',
'$state',
'$status',
'$instituteid',
'$contactemail',
'$bandwidth',
'$institutehead',
'$contactNumber',
'$contactlandlinenumber',
'$latitude',
'$longitude',
'$clientip',
'$name',
'$currentdate',
'$currenttime'
)";
In your code
new_data_entry_log(19 property)
But
VALUES(17 values)
This is the main reason. Another reason can be data type issue.
Because you set all values as String/Varchar
Note: best practice(underscore) for database fields
`added by` --> 'added_by'
`added on` --> 'added_on'
`added at` --> 'added_at'
Using Variable in MySQL
I have tried many possibilities and consulted a number of sources but still not have been
able to insert a string into a MySQL command in php.
Code below works well
$SQL = 'INSERT INTO tb_addressbook (`ID`, `First_Name`, `Last_Name`, `Address`) VALUES (\'24\', \'JJ\', \'Gates\', \'Microsoft\');';
Code below does not work
$SQL = 'INSERT INTO tb_addressbook (`ID`, `First_Name`, `Last_Name`, `Address`) VALUES (\'27\', \''.'"$first"'.'\''.', \'Gates\', \'Microsoft\');';
Can you help?
P.S. Is there a special way to insert a string for numbers?
Hugh
hugh#hahaggerty.com
Try like this :
$SQL = "INSERT INTO tb_addressbook (ID, First_Name, Last_Name, Address) VALUES ('27', '".$first."', 'Gates', 'Microsoft')";
I'm using the following php query to install tables in my CMS system:
$q=new mysql("
INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`) VALUES
(0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', 'admin#domain.com');
");
However instead of e-mail admin#domain.com I would like to use e-mail stored inside /settings/contact.inc.php file which is:
<?php
$emailaddress='admin#domain.com';
?>
Simply include the file and use the variable:
require_once("/settings/contact.inc.php");
$q=new mysql("
INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`) VALUES
(0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', '$emailaddress');
");
Beware of SQL injection
In this case you know where $emailaddress, comes from and you can trust the content. In other cases you need to protect your code against SQL injection.
Therefore, I advise you to use prepared statements, using the mysqli functions.
You can then replace the variables in the query by a question-mark or named placeholder:
"INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`) VALUES (0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', ?);"
and bind $emailaddress using the mysqli_stmt_bind_param function.
You can simply use it like,
$query = "INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`)
VALUES (0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', '$emailaddress')";
Note: You need to include /settings/contact.inc.php file.
Do Read: sql injection attacks! Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
You can include the /settings/contact.inc.php and then you can use the $emailaddress variable.
include('/settings/contact.inc.php');
$q=new mysql("INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`) VALUES (0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', '$emailaddress');");
You can include the file and then you can use the all variable like below.
<?php include_once('/settings/contact.inc.php'); ?>
All the answers was great so i voted up all of them. Besides that way that everyone suggested you can do it by using fopen and fread. I know that way is simple way, but my way is just another way.
$filePath = './settings/contact.inc.php';
$handle = fopen($filePath,"r+");
$content = fread($handle,filesize($filePath));
$array = explode(" ",$content);
foreach($array as $word)
{
if(filter_var($word, FILTER_VALIDATE_EMAIL))
{
$emailaddress = $word;
}
}
fclose($handle);
$q=new mysql("INSERT INTO `adm` (`id`, `login`, `adm`, `passwd`, `czas`, `logged`, `ip`, `email`)
VALUES
(0, 'admin', 1, PASSWORD('admin'), 0, 0, '0.0.0.0', '$emailaddress');");
I'm trying to execute a prepared sql request wich should insert values into a variable table
This code will be more explicite than me :
$req = $db->prepare("INSERT INTO ?
( `id`,
`parent_id`,
`position`,
`left`,
`right`,
`level`,
`title`,
`type`,
`content` )
VALUES (NULL,
'2',
'last',
'3',
'10',
'2',
?,
'default', ?);");
$req->execute(array($_SESSION["user_id"], $result["title"], $result["content"]));
All variables are set, I checked that with some echo.
Isn't it possible to "INSERT INTO" a variable ?
(Each user has its own table named by its unique id, that's why I can't directly write the table name in the query)
You can't use a named parameter for a table name; if you want to do that, you'll have to include the name in your SQL directly:
INSERT INTO $tablename (....
However - that's still open to SQL injection attacks.
If you want to store data like that, I'd put everything into a single table, and just add an extra field as an additional key.
No, you can't do this, you need to do like below.
$table = $_SESSION["user_id"];
$req = $db->prepare("INSERT INTO $table (`id`, `parent_id`, `position`, `left`, `right`, `level`, `title`, `type`, `content`) VALUES (NULL, '2', 'last', '3', '10', '2', ?, 'default', ?);");
$req->execute(array($result["title"], $result["content"]));
I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id