2

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql. now i want to post more information to mysql using where clause (form data) in sql statement.

This is my code to submit and post data.

<script  src="jquery.min.js"></script>       
<script type="text/javascript">
$(function() {
        var addDiv = $('#addinput');
        var i = $('#addinput p').size() + 1;

        $('#addNew').live('click', function() {
                $('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select><a href="#" id="remNew">Remove</a> </p>').appendTo(addDiv);
                i++;


                return false;
        });

        $('#remNew').live('click', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

</script>

<body>


<?php if (!isset($_POST['submit_val'])) { ?>
 <h1>Add your Hobbies</h1>
 <form method="post" action="">

 <div id="container">
 <p id="addNew"><a href="#"><span>Add New</span></a></p>
 <div id="addinput">

 <input type="submit" name="submit_val" value="Submit" />
 </form>
<?php } ?>
<?php

?>


<?php
    if (isset($_POST['submit_val']))
    {
        $stockid = $_POST["stockid"];
        $desc = $_POST["desc"];
        foreach($stockid as $a => $B)
        {
            $query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
        }
        echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
    }
?>

its working fine now when am trying to use a select statement and post data to mysql its not working here is code

<?php
    $con=mysqli_connect("localhost","root","","inventory");

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");

    while($row = mysqli_fetch_array($result))
    {
      echo $row['price'];
    }

    mysqli_close($con);
?>

then i modify the post code of above file like this

<?php    
    if (isset($_POST['submit_val']))
    {
        $stockid = $_POST["stockid"];
        $desc = $_POST["desc"];
        $price = $row['price'];
        foreach($stockid as $a => $B)
        {
            $query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
        }
        echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
    }
?>

but nothing is inserted in to database in price column

1
  • $$_POST is intentional ? Commented Jan 20, 2014 at 11:06

2 Answers 2

1

Change your code to store the price value in a new variable:-

<?php
    $con=mysqli_connect("localhost","root","","inventory");
    $price = array(); //declare

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");

    while($row = mysqli_fetch_array($result))
    {
      echo $row['price'];
      $price = $row['price']; //initiate
    }

    mysqli_close($con);
?>

<?php    
    if (isset($_POST['submit_val']))
    {
        $stockid = $_POST["stockid"];
        $desc = $_POST["desc"];


            $query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);

    }
?>

Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.

Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.

Also, as the other guys have said remove the double $$ and just use one on this line:-

$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");

Hope this is of some help to you :)

Sign up to request clarification or add additional context in comments.

4 Comments

it is showing an error Uninitialized string offset: 0 in C:\xampp\htdocs\abc\add2\index.php on line 128 the line is $query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
See my edit to answer, that should get 1 record inserted for you and then go from there =)
it is inserting record but text array is inserted in database for stockid and description and $price is blank.
If your price is still null, you need to send the values the same way you send your stockid and description values.
1

As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.

But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)

I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :

Change this:

<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");

while($row = mysqli_fetch_array($result))

to this:

<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
  echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will 
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);

Change this:

<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );

to this :

<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);

EDIT : Some documentation: MySQLi

mysqli_prepare (sql queries more protected from sql injection)

mysqli_stmt_bind_param

mysqli_stmt_execute

mysqli_stmt_bind_result

mysqli_stmt_fetch

4 Comments

Heyy thanks, this is the clearest example i've seen so far for prepared statements! It's something I need to start using myself also =)
Just adapted the documentation examples to that case. Personnaly I strongly recommand to use object oriented style, $my = new MySQLi($host, $user, $pass); instead of mysqli_connect
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
I completed the answer (and modified the select query). Sorry I forget to tell you have to use mysql_stmt_fetch and mysql_stmt_bind_result instead of fetch_array. I also added the uses of mysql_stmt_error. See the php documentation I added at the end of the post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.