0
votes

I have a problem regarding "no prompted error and data cannot insert into child table".

I have 2 tables (users and useradvert); - The users is the PARENT - The useradvert is the CHILD

  1. users (parent table-ID is primary key with auto increment)

    • ID
    • name
    • username
    • telno
    • password
    • date (timestamp)
  2. useradvert (child table-ID is index with NO auto increment)

    • ID
    • name2
    • color2
    • hobby2

I have no problems creating a relation table. The 2 tables are now related.

Then I have a login page (login.php) - runs fine no problem..

And I have a user page (useracc-test.php)-> this is a page after a user log in successfully via login.php. They will be able to view their personal data and also enter their name again (any different nick name they like), color and hobby.This page display user's personal data and secondly, there is also a form where users can enter data like I said previously(name2,color and hobby).

I have no problem displaying the user's personal data in the user page (useracc.test.php). This data is retrieved from parent table "user". The problem I'm having is, I cannot insert data into the child table (useradvert). No error prompted.

<?php    
//useracc-test.php    
/**
 * Start the session.
 */
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);
// require 'lib/password.php';
require 'connect-test.php';   

$userName= isset($_POST['username']) ? $_POST['username'] : '';    

$query = "SELECT id, name, username, telno FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $userName);
$stmt->execute();
$res = $stmt->get_result();
 ?>    
<html>
<head>
<style type="text/css">
#apDiv2 {
    position: absolute;
    left: 51px;
    top: 238px;
    width: 237px;
    height: 93px;
    z-index: 1;
}
#apDiv1 {
    position: absolute;
    left: 134px;
    top: 123px;
    width: 234px;
    height: 104px;
    z-index: 2;
}
#apDiv3 {
    position: absolute;
    left: 58px;
    top: 146px;
    width: 219px;
    height: 61px;
    z-index: 2;
}
#apDiv4 {
    position: absolute;
    left: 302px;
    top: 102px;
    width: 365px;
    height: 123px;
    z-index: 3;
}
</style>
<link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css">
<script src="SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script>
</head>
<body>
Your Personal details:</p>
      <p><?php while($row = $res->fetch_array()): ?>
<p><?php echo $row['id']; ?></p>
<p><?php echo $row['name']; ?></p>
<p><?php echo $row['username']; ?></p>
<p><?php echo $row['telno']; ?>





  <?php     

  // $userid = $_POST['id'];
  $stmt=$conn->prepare("INSERT INTO useradvert (id,name2,color2,hobby2) VALUES (?,?,?,?)");
  $stmt->bind_param("isss", $id, $name2, $color2, $hobby2);
  $stmt->execute();
  if (!$stmt)
  { printf("Errormessage: %s\n", $mysqli->error);}
  else {

  echo "New records created successfully";}

$stmt->close();
$conn->close();

    ?>      

<form name="form2" method="post" action="useracc-test.php">
        <p>INSERT YOUR INTEREST:</p>
        <p>     
        </p>
          ID:
      <input name="id" type="hidden" id="id" value="<?php echo $row['id']; ?>">


  <p>Name :
          <input type="text" name="name2" id="name2">
        </p>
        <p>
          <label for="warna2"></label>
          Color :
          <input type="text" name="color2" id="color2">
        </p>
        <p>
          <label for="hobi2"></label>
          Hobby:
          <input type="text" name="hobby2" id="hobby2">
        </p>
        <p>
          <input type="submit" name="submit" id="submit" value="submit">
       </p>
        <p>&nbsp;</p>
      </form>       

               <?php endwhile; ?>

               </body>
               </html> 
--
-- Table structure for table `useradvert`
--

CREATE TABLE IF NOT EXISTS `useradvert` (
  `id` int(10) unsigned NOT NULL,
  `name2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `color2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `hobby2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `telno` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
  `username` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=96 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `telno`, `username`, `password`, `date`) VALUES
(95, 'Test Name', '09999999999', '[email protected]', '$2y$12$fqdmAQk5c8qk8Eh2TWy2n.AdNO.lFjqmi2ruSzk8tsVXcK71OcPae', '2015-12-24 05:00:13');

--
-- Constraints for dumped tables
--

--
-- Constraints for table `useradvert`
--
ALTER TABLE `useradvert`
  ADD CONSTRAINT `useradvert_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`);
4
Im looking for solutions and asnwers.. but I keep getting "strike through" from some people..I'm not sure either you are helping........ hosnestly.it doesn't help me at this time.. and please don't play around.. - Linda May
Hopefully.. someone generous out there can be sincere and honest ..instead of marking down here and there without any explanations...this is a community for finding solutions..hopeefully.. some users can observe online decorum... - Linda May
Please read: stackoverflow.com/help/how-to-ask - We don't need to know about your headache. Keep it short and to the point, follow the protocol for asking questions and you will get answers. It's a great community if you take the time to be a good member of it. - I wrestled a bear once.
Ok noted.. I apologise for that.. I'm still new to this site... - Linda May
Tq Pamblam...but I got this error just now after logging in..-->>mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\eventsite\useracc-test.php on line 25 Your Personal details: - Linda May

4 Answers

0
votes

In your connection you're using mysqli, in your query you're using mysql_

$query = sprintf("select name, username, telno FROM users WHERE username='%s'", mysqli_real_escape_string($conn, $userName));

(Change to mysqli_real_escape_string)

0
votes

The first problem, as lucap stated, is that you try to insert data in a table with no auto increment ID, without providing that ID. if you look at the mysqli error you should with print($conn->error); you should see an error message about that.

But there is some other errors in your script that make it fail. Let's take this step by step.

$query = sprintf("select name, username, telno FROM users WHERE username='%s'", mysql_real_escape_string($userName));
$result = $conn->query($query);

You should test the password in this query, as right now it consider as logged an user who just send as post data the username, which is a severe security issue. Beside that, there is two error: you don't get the ID of the user in the query, and mysql_real_escape_string is deprecated. Considering you're using mysqli, I suggest to proceed in this way to sanitize input data:

$sql = sprintf("SELECT ID, name, username, telno FROM users WHERE username = '%s' AND password = '%s'", mysqli_real_escape_string($conn, $_POST['username']), mysqli_real_escape_string($conn, $_POST['password']));
$result = $conn->query($sql);
$result = $result->fetch_row();

Of course you should hash the password with the appropriate encryption you're using, because of course you don't store the password raw :)

So this:

<?php while($row=$result->fetch_assoc()): ?>
    <?= $row['name'] ?>
</p>
<p>
    <?= $row['username'] ?>
</p>
<p>
<?= $row['telno'] ?>
<?php endwhile; ?>

Will become:

<p><?php echo $row['name']; ?></p>
<p><?php echo $row['username']; ?></p>
<p><?php echo $row['telno']; ?>

So let's get on what you stumbled upon:

$sql = "INSERT INTO useradvert(name2,color2,hobby2)VALUES('$name2', '$color2','$hobby2')";
if ($conn->query($sql) === TRUE) {
    if (isset($_POST['submit'])){
        $name2=$_POST['name2'];
        $color2=$_POST['color2'];
        $hobby2=$_POST['hobby2'];
        echo "You have succesfylly inserted your data. Insert another data again?";
    } 
    else 
    {
        die ("Error: " . $sql . "<br>" . $conn->error );
    }

    $conn->close();
}

This can't work for the following reasons:

  1. As stated above you don't provide the ID.
  2. $name2, $color2 and $hobby2 just contain true because of this:

    $name2=isset($_POST['name2']);
    $color2=isset($_POST['color2']);
    $hobby2=isset($_POST['hobby2']);
    

    I guess what you wanted to do was in fact:

    $name2  = isset($_POST['name2']) ? $_POST['name2'] : '';
    $color2 = isset($_POST['color2']) ? $_POST['color2'] : '';
    $hobby2 = isset($_POST['hobby2']) ? $_POST['hobby2'] : '';
    

And beside those two points, this query isn't secure as it insert raw data in the query. So the final code would be:

$sql = sprintf("INSERT INTO useradvert (ID, name2, color2, hobby2) VALUES (%d, '%s', '%s', '%s')", (int)$result['ID'], mysqli_real_escape_string($conn, $name2), mysqli_real_escape_string($conn, $color2), mysqli_real_escape_string($conn, $hobby2));
if($conn->query($sql) === true) {
    // do your stuff
}

I think that's all, but if you still encounter issues after fixing all this, I suggest to check on $conn->error to see any error from mysqli, and do var_dump of your data to see if everything is ok. Be sure too that you turned on php errors with the following:

ini_set('display_errors', 1);
error_reporting(E_ALL);
0
votes

I solved the problem myself... I forgot the if(isset($_POST['submit']))..LoL.I did some minor changes just to add the isset above.. everything works fine now..

-1
votes

you must specify the id in your insert statement. add id in select statement

$query = sprintf("select id,name, username, telno FROM users WHERE username='%s'", mysql_real_escape_string($userName));

and then:

$id=$row['id'];
$sql = "INSERT INTO useradvert(id,name2,color2,hobby2)VALUES('$id','$name2', '$color2','$hobby2')";