MerlinJR Posted October 9, 2009 Share Posted October 9, 2009 So I'm trying to update grade in grade table, at the same time if there was NO grade INSERT it into the table. basically, before this file, I have a form with drop down box so a user can pick student ID and courses then update or insert grade. I didn't get any error message but it didn't update or insert grade to my table. anybody have any idea what is wrong with my code? Thanks 4 your help. <?php $host = 'localhost'; $user_name = 'xxx'; $password = 'xxx'; $data_base = 'xxx'; $student = 'student'; $course = 'course'; $grade = 'grade'; $connect = @mysqli_connect ($host, $user_name, $password, $data_base) or die('Error connecting to mysql'); $query = "SELECT grade FROM grade WHERE stu_id = '$_POST[stu_id]' AND cours_num ='$_POST[cours_num]' "; $result = mysqli_query($connect, $query); if (mysqli_num_rows($result) > 0) { $result = mysqli_query($connect, "UPDATE grade SET grade = '$_POST[cours_num]' WHERE stu_id = '$_POST[stu_id]' AND cours_num = '$_POST[cours_num]'"); echo "<h1 align=\"center\">Grade Completed</h1>"; } else { $result = mysqli_query($connect, "INSERT INTO grade (grade) VALUES '$_POST[grade]'"); echo "<h1 align=\"center\">Grade Completed</h1>"; } ?> <html> <head> <style type="text/css"> .center {text-align:center} </style> </head> <body> <p class="center"><br/><br/><a href="grade.php">Edit/Add Another Record?</a></p> <p class="center"><a href="..">Go back to the main form</a></p> </body> </html> Quote Link to comment Share on other sites More sharing options...
ameyemad Posted October 9, 2009 Share Posted October 9, 2009 maybe try $result = mysqli_query($connect, "UPDATE grade SET grade = '$_POST[cours_num]' WHERE stu_id = '$_POST[stu_id]' AND cours_num = '$_POST[cours_num]'"); if (!mysqli_affected_rows()){ $result = mysqli_query($connect, "INSERT INTO grade SET grade='$_POST[grade]'") or die(mysqli_error()); } Quote Link to comment Share on other sites More sharing options...
xsist10 Posted October 9, 2009 Share Posted October 9, 2009 Firstly you are inserting a new record with just a grade and no stu_id. Also please escape all user input (use mysql_real_escape_string() if in doubt or cast to int if you know the value must be an integer). "INSERT INTO grade (grade, stu_id, cours_num) VALUES ('". mysql_real_escape_string($_POST[grade]) ."', '". mysql_real_escape_string($_POST[stu_id]) ."', '". mysql_real_escape_string($_POST[cours_num]) ."')"; You can also use MySQL's built in ON DUPLICATE option to save yourself some time. http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.