Hi, I am new to Javascript and PHP and I am trying to duplicate some data and store it in a database when users clicked on the "copy button".

Click Here

With reference to the image(click on the link above), upon clicking "copy trade" the data will be replicated into the database.

How can this be done through Javascript or PHP? Thanks.

Recommended Answers

All 9 Replies

One way to do this is to use hidden input, but a better way to do this is using sql queries. Like this:

INSERT INTO trade_copy ( title,price,etc )
        SELECT  title,post,etc
        FROM    trade
        WHERE tradeID = $theTradeId

Hi, thanks for your reply! I tried your method but the data are not reflected into the database. The data rows are recorded as NULL when I hit the "copy" link. The following are my codes:

homepage.php (this is the page where my users can view or copy the speech)

<?php

    session_start();

    // default user's name
    $user = '';

    // check if visitor is logged in ?
    $loggedIn = (!empty($_SESSION['user']));

    // since user is logged in, let us retrieve user's name from $_SESSION
    if ($loggedIn) {
        $user = $_SESSION['user'];
    } else {
        // we only allow logged in user to see this page
        // if visitor not logged in, redirect visitor to login page
        header('Location: index.php');
        exit;
    }

    require_once('config/database.php');

    // Step 1; CONNECT
    $mysqli = new mysqli($database_hostname, $database_username, $database_password, $database_name) or exit("Error connecting to database"); 

    // Step 2; QUERY
    $stmt = $mysqli->prepare("SELECT * FROM `assignment_speeches`"); 

    // Step 4
    //execute query
    $stmt->execute(); 

    /**
    * No. of variables MUST match no. of COLUMNS retrieved
    * Since in Step 2 we retrieved * meaning ALL the Columns
    * we need to have the same number of variables
    * Currently, assignment_speeches have the following COLUMNS in this exact order
        Column  Type    Comment
        id  int(11) unsigned Auto Increment  
        subject varchar(255) NULL    
        body    text NULL    
        tags    varchar(255) NULL    
        image   varchar(255) NULL
    **/

    // Step 5
    // store all the data fetched from the database
    $stmt->bind_result($id, $subject, $body, $tags, $image);

    //  Step 6
    // change the $students to $speeches
    $speeches = array(); // prepare an empty array to store all the results fetched from database
    while ($stmt->fetch()) {
        // adding the fetched results one by one using the while loop
        $speeches[$id] = array(
            'id'       => $id,
            'subject'  => $subject,
            'body'     => $body,
            'tags'     => $tags,
            'image'    => $image,
        );
    }

    // Step 7
    $stmt->close();

    // Step 8
    $mysqli->close();

    $message = ''; 
    // for displaying successful deletion messages
    if (!empty($_SESSION['message'])) {
        $message = $_SESSION['message'];
        unset($_SESSION['message']);
    }

    $backgroundimage = 'images/speakers.jpg';

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>
            Speech Corner
        </title>
        <meta name="author" content="kim sia"><!-- Date: 2012-04-30 -->
    </head>
    <body>

        <style type="text/css">
        body {
                  background-image: url('<?php echo $backgroundimage; ?>');
                  background-size: 1400px 1200px;
                  background-repeat: no-repeat;

             }
        </style>

        <h1> Welcome to the Speech Corner</h1>
        <h2><?php echo $message; ?></h2>
        <table>

                <?php        
                date_default_timezone_set("Asia/Singapore");
                $date = date('m/d/Y h:i:s a', time());
                $timezone = date_default_timezone_get();
                echo " The current time is: " . $date;
                ?>

                <td style="width: 100%; height: 70%;">
                Please choose a speech you are interested in:<br>
                <table>
                <?php foreach($speeches as $key => $speech) : ?>

                    <?php

                    // here we pick out the values we need
                    $id         = $speech['id'];
                    $subject    = $speech['subject'];
                    $body       = $speech['body'];
                    $tags       = $speech['tags'];
                    $image      = $speech['image'];
                    $viewUrl    = 'speechdetails.php?id=' . $id;
                    $copyUrl    = 'deletespeech.php?id=' . $id;             

                    ?>

                <tr>
                    <td>
                        <img width="200" height="200" src="images/<?php echo $image; ?>" /><br />
                        <?php echo $subject; ?>
                    </td>
                    <td>
                        <a href="<?php echo $viewUrl; ?>"> View </a> | <a href="<?php echo $copyUrl; ?>"> Copy </a> 
                    </td>
                    </tr>
                        <?php endforeach; ?>

                </table>

                </td>
                </tr>
                <tr>
                    <td style="width: 100%; height: 10%;">
                    <font color = "red">Copyright <?php echo date('M'); ?></font>
                    </td>
                </tr>
        </table>
        Click <a href="addspeech.php">here</a> to add speech.
        <br />
        Click <a href="logout.php">here</a> to logout.
    </body>
</html>

copyspeech.php (code for copying the speech. yet, the data recorded into the database are NULL)

<?php

        session_start();

        // default user's name
        $user = '';

        // if visitor is logged in 
        $loggedIn = (!empty($_SESSION['user']));

        // since user is logged in, let us retrieve user's name from $_SESSION
        if ($loggedIn) {
            $user = $_SESSION['user'];
        } else {
            // we only allow logged in user to see this page
            // if visitor not logged in, redirect visitor to login page
            header('Location: index.php');
            exit;
        }


        // the file that contains your database credentials like username and password
        require_once('config/database.php');

        // see Lecture Webp_Week13_14_Using_PHPandMySQL(updating).pptx Slide 4 aka Step 1
        $mysqli = new mysqli($database_hostname, $database_username, $database_password, $database_name) or exit("Error connecting to database"); 

        // Slide 5 aka Step 2
        $stmt = $mysqli->prepare("INSERT INTO assignment_speeches VALUES (?,?,?,?,?)"); 

        // Slide 6 aka Step 3 the bind params must correspond to the ?
        $stmt->bind_param('issss', $speechID, $subject, $body, $tags, $image); // 1 ? so we use i. we use i because  id is INT

        // Slide 7 aka Step 4
        $successfullyDeleted = $stmt->execute(); 

        // Slide 8 aka Step 5
        // we won't check the delete result here.

        // Slide 9 aka Step 6 and 7
        $stmt->close();

        $mysqli->close();

        // if we successfully delete this, we 
        if ($successfullyDeleted) {
            $_SESSION['message'] = 'Successfully deleted';
        } else {
            $_SESSION['message'] = 'Unable to delete';
        }

        header('Location: homepage.php');

?>

//EDIT//

$copyUrl    = 'copyspeech.php?id=' . $id;

u should have in the cpopyspeech.php
if isset $_GET['id'] and ! empty
then mysql query (the query i wrote first);

okay I was replying from my mobile...
In you copyspeech.php, you should retrieve the information passed using the $_GET.
I'm not sure where you want to replicate the information (I mean to which table). But you should have this on your page:

$id = $_GET['id'];

if(isset($_GET['id']) && !empty($_GET['id']) && is_numeric($id)){
    $sql="INSERT INTO assignment_speeches_copy ( id,subject,body,tags,image )
                SELECT id,subject,body,tags,image
                FROM assignment_speeches
                WHERE id = $id";

      mysql_query($sql);
}

You may need to make some modifications but this is the main concept of replicating a data.

May I know where can I include that part of the code in my copyspeech.php? Do I include it in the prepare statement? Sorry, I am rather new to PHP. By the way, I would like to have the replicated information inserted into the same database, assignment_speeches.

<?php

        session_start();

        // default user's name
        $user = '';

        // if visitor is logged in 
        $loggedIn = (!empty($_SESSION['user']));

        // since user is logged in, let us retrieve user's name from $_SESSION
        if ($loggedIn) {
            $user = $_SESSION['user'];
        } else {
            // we only allow logged in user to see this page
            // if visitor not logged in, redirect visitor to login page
            header('Location: index.php');
            exit;
        }


        // the file that contains your database credentials like username and password
        require_once('config/database.php');

        // see Lecture Webp_Week13_14_Using_PHPandMySQL(updating).pptx Slide 4 aka Step 1
        $mysqli = new mysqli($database_hostname, $database_username, $database_password, $database_name) or exit("Error connecting to database"); 


        // Slide 5 aka Step 2
 $stmt = $mysqli->prepare("INSERT INTO assignment_speeches ( id,subject,body,tags,image )
                                        SELECT id,subject,body,tags,image
                                        FROM assignment_speeches
                                        WHERE id = ?"); 

            // Slide 6 aka Step 3 the bind params must correspond to the ?
            $stmt->bind_param("i",$_GET['id']); // 1 ? so we use i. we use i because  id is INT



        // Slide 7 aka Step 4
        $successfullyDeleted = $stmt->execute(); 

        // Slide 8 aka Step 5
        // we won't check the delete result here.

        // Slide 9 aka Step 6 and 7
        $stmt->close();

        $mysqli->close();

        // if we successfully delete this, we 
        if ($successfullyDeleted) {
            $_SESSION['message'] = 'Successfully deleted';
        } else {
            $_SESSION['message'] = 'Unable to delete';
        }

        header('Location: homepage.php');

?>

You need to check the rest of the code, it looks like it was a delete a record page. Try this, but you need to secure it by restricting the variable passed to accept only integer values, otherwise it will redirect to 'X.php'or display an error.

Okay, however, the bind_param part has an error. It says "Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\1102824H\Assignment2\copyspeech.php on line 35"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.