-1

I have a web application in which students are divided into "batches".

I am trying to insert student for particular batch and the batch will be chosen by user by select option. After that student is added to the particular batch, he/she will be added to stdhold table. However, it is only inserting for the first selected value of select option.

<?php  
function specialCOn() {
    $connew = mysqli_connect("localhost","root","");
    $db = mysqli_select_db($connew,'mcqs');
    return($connew);
}

if (isset($_POST['add'])) 
{
    $namestd=$_POST['std_name'];
    $batchstd=$_POST['batch'];
    $FNAME=$_POST['f_name'];
    $query3 = "INSERT INTO `$batchstd` VALUES('','$namestd','$FNAME')";
    $rsq3 = mysqli_query(specialCOn(),$query3);
    mysqli_close(specialCOn());
    $queryrollno = "select rollno from `$batchstd` order by rollno desc";
    $rsqrollno = mysqli_query(specialCOn(),$querrollno);
    $getrollno = mysqli_fetch_array($rsqrollno);
    $rollnoto = $getrollno[0];
    echo "<script>alert('$batchstd')</script>";
    echo "<script>alert('$rollnoto')</script>";
    mysqli_close(specialCOn());

    //Problem is here
    $querystdhold = "INSERT INTO stdhold VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd')";
    $rsqhold = mysqli_query(specialCOn(),$querystdhold);
    mysqli_close(specialCOn());

    if ($rsq3&&$rsqhold) 
    {
         echo "<script> alert('Student Added.');
         window.location.assign('addstudent.php');
     </script>";

    //header('Location:addstudent.php');
}
else
{
    echo "<script> alert('You Havenot added Student.');
    window.location.assign('addstudent.php');</script>";
}
}
?>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Use [prepared statements](http://php.net/manual/en/mysqli.prepare.php). – Tom Fenech Apr 05 '15 at 11:41
  • You have SQL injection vulnerabilities against the root user in your database, which means that even unrelated applications on the same server can be tampered with remotely. Also, your indentation needs fixing - it is presently hard to read. – halfer Apr 05 '15 at 11:43

2 Answers2

0

Try specifying the column names in your insert query:

INSERT INTO stdhold (col1, col2, col3, col4) VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd');

For reference see the MySQL Insert documentation.

Steve
  • 380
  • 1
  • 9
0

Try use this :

$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO ? (col1,col2,col3) VALUES('',?,?)");
$stmt->bind_param('sss', $_POST['batch'], $_POST['std_name'], $_POST['f_name']);
$stmt->execute();

For the detail example you need to read the @Amber Answer how to create secured prepared statement.

Hope this'll help you.

Community
  • 1
  • 1
Eko Junaidi Salam
  • 1,663
  • 1
  • 18
  • 26