Cash
Cash

Reputation: 5

How do I use SESSION data to SELECT 1 database entry and then INSERT into another table with data from a form as well with PHP and MySQL?

All security issues aside.


I am trying to get some data retrieved from a query (using the session data) to be put in with the form data that has been submitted.

Essentially create a record of who submitted the data.

Here is my code:

<?php
session_start();
if ( isset( $_SESSION['user'] ) ){
  header("location:failedlogin.html");
}
echo $_SESSION['myusername'];
var_dump($_SESSION);

//Connect
$con= mysql_connect("localhost","root","password");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database1", $con);

//create Get UserId from user
$result= mysql_query("SELECT UserId FROM user
WHERE UserName='{$_SESSION['myusername']}'");

//I think this is where the problem is 
//execute query and store results
if($result){
  $data = mysql_fetch_assoc($result);
}

//insert form data and $data into database 1
$sql="INSERT INTO bug 
(bugName, bugBy, bugPriority, bugFor, bugContainer, bugFixed, bugCommentCount)
VALUES ('$_POST[bugname]','$data[0]','$_POST[bugpriority]',
        '$_POST[bugfor]','$_POST[bugcontainer]','0','0')";

if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
mysql_close($con)
?> 

I can't seem to get get it to submit the data from the SELECT query, the form data goes through fine.

Sorry if I've laid this out terribly. I'm finding it hard to understand what I've done wrong, so I don't know how to explain what I'm looking for very well.

Thanks for any and all help! Let me know if you need more information.

Upvotes: 0

Views: 1196

Answers (2)

AlexP
AlexP

Reputation: 9857

Your SQL statement is incorrect, the variables require escaping.

"...VALUES('". $_POST['bugname'] . "')";

As you currently have it $_POST[bugname] will try to find a constant global variable called 'bugname'. This will not exist.

However, $_POST['bugname'] will reference the correct key within the array.

I have to mention that this is not only a terrible way to create a SQL statement, It is also very insecure.

Upvotes: 2

Joao
Joao

Reputation: 2746

You're using fetch_assoc, so it's returning an associative array:

instead of $data[0]

insert $data['UserId']

If that doesn't do it, have you check to see if $data has anything before your insert statement?

p.s. you should learn PDO: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Upvotes: 0

Related Questions