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');");
Related
I know questions like this exist all over, but I can't see what's wrong with my code. The DB works and I run an update query just fine earlier on in the code.
Query 1:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'success', NOW()");
Query 2:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'failure', NOW()");
Here is an echo of the string as requested:
INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('AAL', '**.60.**.**', 'c-174-**-**-**.hsd1.**.comcast.net', 'Town, US', 'success', NOW()
Looks like you are missing the final closing ). Also use prepared statements. Much cleaner and safer. Here is a quick example of what a Prepared Statement would look like (adapted from here) (you wold also need to make other changes to your PHP script to start using them)
$stmt = $mysqli->prepare("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES (?, ?, ?, ?, ?, NOW())")
$stmt->bind_param('sssss', $login, $ip, $details->hostname, $loc, 'failure');
$stmt->execute()
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 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.
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
I have a strange problem, I'm sending an SQL query through PHP:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
And it throws me this error:
Invalid query: Column count doesn't match value count at row 1.
Although, when I paste and run the same exact query in PhpMyAdmin, it works perfectly, so it got me quite confused...
I counted the number of columns and the the number of values, and they match (19). I tried to remove the 'id' field, since it's auto-incremented, but it didn't change anything. What am I doing wrong? And why does it work in PhpMyAdmin?
Thanks for any help!
EDIT:
here's the php code:
$values = array('', 1, $lastUpdated, $entry_date, $entry_ip, $streetName, $cityId, $listing['stateorprovince'], $listing['postalcode'], $listing['type'], $listing['listprice'], $has_garage, $has_indoor_parking, $has_outdoor_parking, $has_pool, $has_fireplace, $average_nb_room, $listing['yearbuilt'], $listing['exteriortype']);
$q = "INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('".htmlentities(implode("','",$values),ENT_QUOTES)."')";
$this->execMysqlQuery($q);
and the method that is being called:
private function execMysqlQuery($q, $returnResults = false, $returnInsertId = false){
$c = mysql_connect(DB_SERVER,DB_LOGIN,DB_PASSWORD);
mysql_select_db(DB_NAME, $c);
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error(). "<br/>=>".$q);
}
if ($returnInsertId)
return mysql_insert_id();
mysql_close($c);
if ($returnResults)
return $result;
return true;
}
And the error:
Invalid query: Column count doesn't match value count at row 1
=>INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`) VALUES ('','1','2010-10-27 13:47:35','2010-10-27 13:47:35','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
If you print $q, I'm willing to bet it'll look like this:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding');
(I don't have PHP at work; this is a guess)
In other words, htmlentities is turning your quotes into HTML Entities. Specifically, turning ' to '
Don't use htmlentities on things that aren't being sent to the web browser. Use your database driver's escaping method (mysql_real_escape_string) on each individual value being sent in.
Edit: Better yet, use prepared statements and data binding with MySQLi or PDO, which will automatically escape the data as you bind it.
if ($insert) {
$query = "INSERT INTO employee VALUES ($empno,'$lname','$fname','$init','$gender','$bdate','$dept','$position',$pay,$dayswork,$otrate,$othrs,$allow,$advances,$insurance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno,lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}
include 'include/dbconnection.php';
$result=mysql_query ($query,$link) or die ("invalid query".mysql_error());