Am attempting to update multiple records in a table all at once when a user clicks on the submit button of the form. My code only updates the first row and does nothing to the rest, no error. Below is the code am working with on post
<?php
if (isset($_POST['submit'])) {
$subject_id = $_POST["subject_id"];
$student_id = $_POST["student_id"];
$test1 = $_POST["test1"];
$test2 = $_POST["test2"];
$test3 = $_POST["test3"];
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE records SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
if ($result) {
redirect_to("dashboard.php");
} else {
echo 'MySQL Error: ' . mysqli_error($connection);
exit;
}
}
}
?>
What could be responsible for only the first row being updated and the others ignored? Questions similar to multiple row update haven't helped much as they seem different from what am trying to do here.
In loop you made redirect_to("dashboard.php"); so it probably exit the loop ;)
Redirect condition placed wrongly. Find the below code.
if (isset($_POST['submit'])) {
$subject_id = $_POST["subject_id"];
$student_id = $_POST["student_id"];
$test1 = $_POST["test1"];
$test2 = $_POST["test2"];
$test3 = $_POST["test3"];
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE records SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
if (!$result) {
break;
}
}
if(!$result){
echo 'MySQL Error: ' . mysqli_error($connection);
exit;
}
else {
redirect_to("dashboard.php");
}} ?>
Related
I'm new about the PHP. I create a login form and after I fill up all the input fields. I clicked "SUBMIT" and then it says.. "Column count doesn't match value count at row 1". anybody help me about this. I'm stack with this almost 1 week.. here is my code. and my db connection.
<?php
$connection = mysqli_connect("localhost","root","","db_violation");
function DBCon(){
try{
$connection = new PDO("mysql:host=localhost;port=3306;dbname=db_violation;","root","");
return $connection;
}catch(PDOException $e){echo "Connection failed: ".$e->getMessage();}
}function DBDiscon(){return $connection = null;}
?>
<?php
include '../../PROCESS/dbconnect/dbconnect.php';
$datauserssystems = json_decode(file_get_contents("php://input"));
$user_firstname = mysqli_real_escape_string($connection, $datauserssystems->user_fname);
$user_middlename = mysqli_real_escape_string($connection, $datauserssystems->user_mname);
$user_lastname = mysqli_real_escape_string($connection, $datauserssystems->user_lname);
$user_address = mysqli_real_escape_string($connection, $datauserssystems->user_address);
$user_positionss = mysqli_real_escape_string($connection, $datauserssystems->user_positions);
$user_age = mysqli_real_escape_string($connection, $datauserssystems->user_age);
$user_username = mysqli_real_escape_string($connection, $datauserssystems->user_uname);
$user_userpass = mysqli_real_escape_string($connection, $datauserssystems->user_pwd);
$tableRows = DBCon()->prepare("SELECT COUNT (*) AS row FROM sb_account");
$tableRows->execute();
$count = $tableRows->fetch();
$count = ($count["row"]+1);
$gain ="SbAdmin";
$encrpt = md5($gain.$user_userpass);
$security = DBCon()->prepare("INSERT INTO sb_account_security VALUES('".$count."','".$encrpt."','".$user_userpass."')")->execute();
$sbuserssssquery = mysqli_query($connection, "SELECT * FROM sb_account WHERE sb_username='$user_username'");
$sbuserssssarray = mysqli_fetch_array($sbuserssssquery);
$sbuserssss = $sbuserssssarray['sb_username'];
if($sbuserssss == $user_username) {
echo "sbtwice";
die();
}
else {
mysqli_query($connection, "INSERT INTO sb_account (sb_firstname,sb_middlename,sb_lastname,sb_fullname,sb_address,sb_position,sb_age,sb_username,sb_password) VALUES ('$user_firstname','$user_middlename','$user_lastname','$user_address','$user_positionss','$user_age','$user_username','$encrpt')");
if(mysqli_affected_rows($connection) > 0) {
echo "AddUserSystem";
die();
}
else {
echo mysqli_error($connection);
die();
}
}
?>
Your mysql insert query has issue:
INSERT INTO sb_account
(sb_firstname,
sb_middlename,
sb_lastname,
sb_fullname,
sb_address,
sb_position,
sb_age,
sb_username,
sb_password)
VALUES ('$user_firstname',
'$user_middlename',
'$user_lastname',
'$user_address',
'$user_positionss',
'$user_age',
'$user_username',
'$encrpt');
Here you have 9 columns but are supplying 8 values. You are not passing value for sb_fullname column.
I am new to mysql and php and i am self taught so there is no one to put me through. How can i remove this insertion process in my php file whenever i insert, because it is inserting well but i want to remove the process.
My PHP code is below
<?php
if(isset($_POST['insert_quiz'])) {
var_dump($_POST);
$quiz_add_id = $_SESSION['quiz_id'];
$count = $_SESSION['quiz_no'];
if (
!empty($_POST['question']) && !empty($_POST['optionA']) && !empty($_POST['optionB']) && !empty($_POST['optionC']) && !empty($_POST['optionD']) && count($_POST['op1']) === count($_POST['question']))
{
$question_array = $_POST['question'];
$optionA_array = $_POST['optionA'];
$optionB_array = $_POST['optionB'];
$optionC_array = $_POST['optionC'];
$optionD_array = $_POST['optionD'];
$op1_array = $_POST['op1'];
for ($i = 0; $i < $count; $i++) {
$question = $question_array[$i];
$op1 = $op1_array[$i];
$optionA = mysqli_real_escape_string($connection, $optionA_array[$i]);
$optionB = mysqli_real_escape_string($connection, $optionB_array[$i]);
$optionC = mysqli_real_escape_string($connection, $optionC_array[$i]);
$optionD = mysqli_real_escape_string($connection, $optionD_array[$i]);
$query = "INSERT INTO quizzes (quiz_add_id, quiz_question, quiz_option_A, quiz_option_B, quiz_option_C, quiz_option_D, quiz_option_correct)";
$query .= "VALUES ('{$quiz_add_id}', '{$question}', '{$optionA}','{$optionB}','{$optionC}','{$optionD}', '{$op1}')";
$create_quiz_query = mysqli_query($connection,$query);
}
if(!$create_quiz_query ) {
die('QUERY FAILED' . mysqli_error($connection));
}
//
}
}
?>
THis is what i dont want to see anymore when i insert
remove below code
var_dump($_POST);
In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
I'm trying to fetch couple of single data in my server database but this is throwing some errors. The incoming data is correct. The search function just don't get completed.
Here's the code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
define('HOST','xxxxxxxxxxx');
define('USER','xxxxxxxxxxxx');
define('PASS','xxxxxxxxx');
define('DB','xxxxxxxxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
$post_id = $_POST['id'];
$buyer_mobile = $_POST['mobile'];
$buyer_name = $_POST['name'];
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysqli_query($con,$sql);
$owner_mobile = $row['mobile'];
$sql = "select name from user where mobile='$owner_mobile'";
$r = mysqli_query($con,$sql);
$owner_name = $row['name'];
$sql = "INSERT INTO flat_booking (post_id,owner_mobile,owner_name,buyer_mobile,buyer_name) VALUES ('$post_id','$owner_mobile','$owner_name','$buyer_mobile','$buyer_name')";
if(mysqli_query($con,$sql)){
echo "Success";
}
else{
echo "error";
}
mysqli_close($con);
}else{
echo 'error1';
}
What am I doing wrong here? Maybe this:
$owner_mobile = $row['mobile'];
Thanks in advance!
create table flatower and add mobile column
$post_id = 1;
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysql_query($con,$sql);
$row = mysql_fetch_array($res);
$owner_mobile = $row[0]['mobile'];
Your problem is this line:
$owner_mobile = $row['mobile'];
You have not created the $row variable. For this you would need to do something such as:
Do this first:
<?php
$row = array();
while ($result = mysqli_fetch_assoc($res))
{
$row[] = $result;
}
?>
This allows you to do this:
<?php
foreach ($row as $r)
{
var_dump($r); print "<br />"; // One row from the DB per var dump
}
?>