Jump to content

Update multiple records in PHP / MYSQL


EarthDay

Recommended Posts

Hi there,

I am trying to update a multiple rows for a single column and the code that I have wrote runs through fine and does not show any error messages but does not update the rows or column.

<?php
require_once __DIR__ . "/DataSource.php";
$database = new DataSource();
$sql = "SELECT * FROM contacts";
$result = $database->select($sql);
?>
<html>
<head>
<title>Users List</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/table.css" />
<script language="javascript" src="function.js" type="text/javascript"></script>
</head>
<body>
	<div class="phppot-container">
		<h1>Users List</h1>
		<form name="frmUser" method="post" action="">
			<div id="message"><?php if(isset($message)) { echo $message; } ?></div>
			<table class="striped">
				<thead>
					<tr class="listheader">
						<th></th>
						<th>Username</th>
						<th>Status</th>
					</tr>
				</thead>
<?php
if (is_array($result) || is_object($result)) {
    foreach ($result as $i => $value) {
        if ($i % 2 == 0)
            $classname = "evenRow";
        else
            $classname = "oddRow";
        ?>
<tr class="<?php if(isset($classname)) echo $classname;?>">
					<td><input type="checkbox" name="contacts[]" value="<?php echo $result[$i]["id"]; ?>"></td>
					<td><?php echo $result[$i]["name"]; ?></td>
					<td><?php echo $result[$i]["status"]; ?></td>
				</tr>
<?php
        $i ++;
    }
}
?>
                <tr>
					<td colspan="4"><input type="button" name="update" value="Update"
						onClick="setUpdateAction();" /> <input type="button" name="delete"
						value="Delete" onClick="setDeleteAction();" /></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

update.php

<?php
require_once __DIR__ . "/DataSource.php";

require_once __DIR__ . "/DataSource.php";

$database = new DataSource();
$rowCount = count($_POST["contacts"]);
for ($i = 0; $i < $rowCount; $i ++) {
    $query = "UPDATE contacts SET status = InProgress WHERE id=?";
    $paramType = "i";
    $paramValue = array(
        $_POST["users"][$i]
    );

}
header("Location:index.php");
exit();
?>

Any help would greatly be apprciated.

Cheers, ED.

Edited by EarthDay
Link to comment
Share on other sites

You don't have a form input named 'users' and you never actually execute the query. That's a couple of several issues I see with this code - first, I assume your php is being called via ajax from the JS setUpdateAction() function? If so, you'll want to echo output and let your javascript handle the return instead of issuing a location header. Also, one of the joys about prepared statements is that you can prepare them once and use them multiple times - if you're doing the update in a loop prepare the statement before the loop, then bind and execute it in the loop. Also, if you're using mysqli I recommend switching to PDO now - it's just a better interface. Beyond that, you don't need two consecutive require_once statements for the same file; the name pretty much says it all (require once), and there's no need to jump through the hoops you're doing to assign evenRow or oddRow class names - just use CSS's nth-child() selectors.

Link to comment
Share on other sites

Thanks for the advise @maxxd :)

I have resolved this by adding the amending the code to the following;

<?php
require_once __DIR__ . "/DataSource.php";

$database = new DataSource();
$rowCount = count($_POST["contacts"]);
for ($i = 0; $i < $rowCount; $i ++) {
    $query = "UPDATE `contacts` SET `status` = 'NoShow' WHERE id=?";
    $paramType = "i";
    $paramValue = array(
        $_POST["contacts"][$i]
    );
        $isUpdated = $database->update($query, $paramType, $paramValue);
}
header("Location:index.php");
exit();
?>

The issue that I am having now is that the I have 3 buttons on the bottom of the page that link to different update options and only 2 of them are working, the 3rd one does nothing;

Code on JS Fiddle

As far as I know, everything looks right and can't see any reason why it would stop working on the 3rd button.

Cheers, ED.

Link to comment
Share on other sites

That's a completely different form in the JS Fiddle than what you've described already. Post the code and we can help.

Some more things right off the top, don't set the form 'action' attribute based on what button's clicked - use the JS to set a hidden field in the form and leave the action attribute empty. That way the form will submit to the current URL. Set up your page in this order from top to bottom:

PHP
HTML
JavaScript

This allows you to handle the form submission first and display any errors to the user. It also allows you to not have to maintain three separate files for very similar functionality. Also - as I said before - prepare the query before the loop, then set $paramValue and execute the query in the loop. This way you're not wasting cycles preparing the same statement on every iteration - it only needs to be done once.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.