Welcome to Dream.In.Code
Getting PHP Help is Easy!

Join 136,577 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 1,891 people online right now. Registration is fast and FREE... Join Now!




Insert Calculated Row Value into MYSQL DB

 
Reply to this topicStart new topic

Insert Calculated Row Value into MYSQL DB

ningboring
27 Sep, 2008 - 05:00 AM
Post #1

New D.I.C Head
*

Joined: 27 Sep, 2008
Posts: 5

I have created a simple update form for teachers at my university to mark essays. Teachers enter values and comments (not shown in the code below), the total is then added and stored in the array $tot. The student's name etc are uploaded from an external data source.

I am trying to insert the array ($tot) into my MYSQL database. I think that I need to use implode and/or serialize with INSERT but I have not been able to work out what to do. The ($tot) array contains values computed by adding a number of other values together and is to go into the field 'tot' in my MYSQL database.

The calculation was easy enough, the tricky bit is getting the total ($tot) into the MYSQL database (outputting it to the screen is not hard) - can any one help please? The update form was created with Dreamweaver MX.

My code is as is below:

CODE
<?php require_once('Connections/myconn.php'); ?>
<?php
$currentPage = $HTTP_SERVER_VARS["PHP_SELF"];

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $HTTP_SERVER_VARS['PHP_SELF'];
if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  $editFormAction .= "?" . $HTTP_SERVER_VARS['QUERY_STRING'];
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE results SET name=%s, pro=%s, org=%s, prs=%s, cnt=%s, lng=%s WHERE id=%s",
                       GetSQLValueString($_POST['name'], "text"),
                       GetSQLValueString($_POST['pro'], "int"),
                       GetSQLValueString($_POST['org'], "int"),
                       GetSQLValueString($_POST['prs'], "int"),
                       GetSQLValueString($_POST['cnt'], "int"),
                       GetSQLValueString($_POST['lng'], "int"),
                       GetSQLValueString($_POST['id'], "int"));

  mysql_select_db($database_myconn, $myconn);
  $Result1 = mysql_query($updateSQL, $myconn) or die(mysql_error());
}

$maxRows_rs = 1;
$pageNum_rs = 0;
if (isset($HTTP_GET_VARS['pageNum_rs'])) {
  $pageNum_rs = $HTTP_GET_VARS['pageNum_rs'];
}
$startRow_rs = $pageNum_rs * $maxRows_rs;

mysql_select_db($database_myconn, $myconn);
$query_rs = "SELECT results.id , results.name, results.pro, results.org, results.prs, results.cnt, results.lng FROM results";
$query_limit_rs = sprintf("%s LIMIT %d, %d", $query_rs, $startRow_rs, $maxRows_rs);
$rs = mysql_query($query_limit_rs, $myconn) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);

if (isset($HTTP_GET_VARS['totalRows_rs'])) {
  $totalRows_rs = $HTTP_GET_VARS['totalRows_rs'];
} else {
  $all_rs = mysql_query($query_rs);
  $totalRows_rs = mysql_num_rows($all_rs);
}
$totalPages_rs = ceil($totalRows_rs/$maxRows_rs)-1;

$queryString_rs = "";
if (!empty($HTTP_SERVER_VARS['QUERY_STRING'])) {
  $params = explode("&", $HTTP_SERVER_VARS['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_rs") == false &&
        stristr($param, "totalRows_rs") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_rs = "&" . implode("&", $newParams);
  }
}
$queryString_rs = sprintf("&totalRows_rs=%d%s", $totalRows_rs, $queryString_rs);
?>
<html>
<head>
<title>Update Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr >
      <td>Id:</td>
      <td><?php echo $row_rs['id']; ?></td>
    </tr>
    <tr >
      <td>Name:</td>
      <td><input type="hidden" name="name" value="<?php echo $row_rs['name']; ?>" size="32">
        <?php echo $row_rs['name']; ?> </td>
    </tr>
    <tr >
      <td>Pro:</td>
      <td><input type="text" name="pro"  value="<?php echo $row_rs['pro']; $pro = $row_rs['pro'];?>" size="32">
</td>
    </tr>
    <tr >
      <td>Org:</td>
      <td><input type="text" name="org" value="<?php echo $row_rs['org']; $org = $row_rs['org'];?>" size="32">
      </td>
    </tr>
    <tr >
      <td>Prs:</td>
      <td><input type="text" name="prs" value="<?php echo $row_rs['prs']; $prs = $row_rs['prs'];?>" size="32">
      </td>
    </tr>
    <tr >
      <td>Cnt:</td>
      <td><input type="text" name="cnt" value="<?php echo $row_rs['cnt']; $cnt = $row_rs['cnt'];?>" size="32">
      </td>
    </tr>
    <tr >
      <td>Lng:</td>
      <td><input type="text" name="lng" value="<?php echo $row_rs['lng']; $lng = $row_rs['lng'];?>" size="32">
      </td>
    </tr>
    <tr >
      <td>Tot:</td>
      <td><?php $tot=$pro+$org+$prs+$cnt+$lng;
      echo $tot;
      ?>
        <input name="tot" type="hidden" id="tot" value ="<?php echo $tot?>"></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type="submit" value="Update Record">
      </td>
    </tr>
  </table>
  <input type="hidden" name="MM_update" value="form1">
  <input type="hidden" name="id" value="<?php echo $row_rs['id']; ?>">
</form>
<p>
<table border="0" width="50%" align="center">
  <tr>
    <td width="23%" align="center">
      <?php if ($pageNum_rs > 0) { // Show if not first page ?>
      <a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, 0, $queryString_rs); ?>">First</a>
      <?php } // Show if not first page ?>
    </td>
    <td width="31%" align="center">
      <?php if ($pageNum_rs > 0) { // Show if not first page ?>
      <a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, max(0, $pageNum_rs - 1), $queryString_rs); ?>">Previous</a>
      <?php } // Show if not first page ?>
    </td>
    <td width="23%" align="center">
      <?php if ($pageNum_rs < $totalPages_rs) { // Show if not last page ?>
      <a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, min($totalPages_rs, $pageNum_rs + 1), $queryString_rs); ?>">Next</a>
      <?php } // Show if not last page ?>
    </td>
    <td width="23%" align="center">
      <?php if ($pageNum_rs < $totalPages_rs) { // Show if not last page ?>
      <a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, $totalPages_rs, $queryString_rs); ?>">Last</a>
      <?php } // Show if not last page ?>
    </td>
  </tr>
</table>
</p>
</body>
</html>
<?php
mysql_free_result($rs);
?>


Thanks Ningboring
User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Insert Calculated Row Value Into MYSQL DB
27 Sep, 2008 - 03:28 PM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 3,995



Thanked: 16 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
I'm not quite sure what you are trying to do, you store $tot as a single value, not an array, why would you think you need to use implode?

what columns are in the table you are inserting to?
does the row already exist? if so you could use the syntax for the update SQL call
if the row doesn't exist, it's a simple insert.

also you do not need to connect to the database more than once, unless they are different databases. If they are different although not required good structure would suggest you should close the connection to the previous database before opening another.
User is offlineProfile CardPM
+Quote Post

ningboring
RE: Insert Calculated Row Value Into MYSQL DB
27 Sep, 2008 - 07:54 PM
Post #3

New D.I.C Head
*

Joined: 27 Sep, 2008
Posts: 5

QUOTE(William_Wilson @ 27 Sep, 2008 - 04:28 PM) *

I'm not quite sure what you are trying to do, you store $tot as a single value, not an array, why would you think you need to use implode?

what columns are in the table you are inserting to?
does the row already exist? if so you could use the syntax for the update SQL call
if the row doesn't exist, it's a simple insert.

also you do not need to connect to the database more than once, unless they are different databases. If they are different although not required good structure would suggest you should close the connection to the previous database before opening another.


OK...let me try to be clearer. Yes, there is a column for the total (tot). I tried inserting the value into the database using:

CODE
GetSQLValueString($_POST['tot'], "int"),


This was able to insert the value into the correct column of the database but it didn't insert the most up-to-date value. I am not sure quite how to answer your questions, perhaps the attached screen shots might help. Please bear with me if I seem a bit thick. Thanks.

Attached Image

Attached Image

Ningboring




User is offlineProfile CardPM
+Quote Post

JackOfAllTrades
RE: Insert Calculated Row Value Into MYSQL DB
28 Sep, 2008 - 08:12 AM
Post #4

Cantankerous Old Fart
Group Icon

Joined: 23 Aug, 2008
Posts: 580



Thanked: 59 times
Dream Kudos: 50
My Contributions
GetSQLValueString($_POST['tot'], "int") doesn't do any database updating, it just takes the content of the $_POST variable, sanitizes it and makes it syntactically acceptable for database insertion.

You still have to do the update in a SQL statement like
php
$query = 'UPDATE results SET total = ' . 
GetSQLValueString($_POST['tot'], "int") .
' WHERE id = ' .
GetSQLValueString($_POST['id'], "int");
if (!mysql_query($query, $my_conn))
{
echo ("Unable to update results table with query $query: " . mysql_error());
}

User is offlineProfile CardPM
+Quote Post

ningboring
RE: Insert Calculated Row Value Into MYSQL DB
28 Sep, 2008 - 06:35 PM
Post #5

New D.I.C Head
*

Joined: 27 Sep, 2008
Posts: 5

QUOTE(JackOfAllTrades @ 28 Sep, 2008 - 09:12 AM) *

GetSQLValueString($_POST['tot'], "int") doesn't do any database updating, it just takes the content of the $_POST variable, sanitizes it and makes it syntactically acceptable for database insertion.

You still have to do the update in a SQL statement like
php
$query = 'UPDATE results SET total = ' . 
GetSQLValueString($_POST['tot'], "int") .
' WHERE id = ' .
GetSQLValueString($_POST['id'], "int");
if (!mysql_query($query, $my_conn))
{
echo ("Unable to update results table with query $query: " . mysql_error());
}



Thanks, but does the code below not do the same as your code above?

php
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE results SET name=%s, pro=%s, org=%s, prs=%s, cnt=%s, lng=%s, tot=%s WHERE id=%s",
GetSQLValueString($_POST['name'], "text"),
GetSQLValueString($_POST['pro'], "int"),
GetSQLValueString($_POST['org'], "int"),
GetSQLValueString($_POST['prs'], "int"),
GetSQLValueString($_POST['cnt'], "int"),
GetSQLValueString($_POST['lng'], "int"),
GetSQLValueString($_POST['tot'], "int"),
GetSQLValueString($_POST['id'], "int"));
mysql_select_db($database_myconn, $myconn);
$Result1 = mysql_query($updateSQL, $myconn) or die(mysql_error());
}


It is actually updating the field 'tot' but not correctly. If I type: 5, 5, 5, 5, 5 into the update form then hit submit: the onscreen total shows 25. No problem!! If I check the MYSQL database all the individual values have updated but not the total. So I type 5, 5, 5, 5, 6 and hit submit. Again onscreen shows the correct value and all of the individual values update in the DB, including the total but it shows as 25 NOT 26. If I hit submit one more time it updates tot to 26.

User is offlineProfile CardPM
+Quote Post

ningboring
RE: Insert Calculated Row Value Into MYSQL DB
29 Sep, 2008 - 07:18 PM
Post #6

New D.I.C Head
*

Joined: 27 Sep, 2008
Posts: 5

QUOTE(ningboring @ 28 Sep, 2008 - 07:35 PM) *

QUOTE(JackOfAllTrades @ 28 Sep, 2008 - 09:12 AM) *

GetSQLValueString($_POST['tot'], "int") doesn't do any database updating, it just takes the content of the $_POST variable, sanitizes it and makes it syntactically acceptable for database insertion.

You still have to do the update in a SQL statement like
php
$query = 'UPDATE results SET total = ' . 
GetSQLValueString($_POST['tot'], "int") .
' WHERE id = ' .
GetSQLValueString($_POST['id'], "int");
if (!mysql_query($query, $my_conn))
{
echo ("Unable to update results table with query $query: " . mysql_error());
}



Thanks, but does the code below not do the same as your code above?

php
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE results SET name=%s, pro=%s, org=%s, prs=%s, cnt=%s, lng=%s, tot=%s WHERE id=%s",
GetSQLValueString($_POST['name'], "text"),
GetSQLValueString($_POST['pro'], "int"),
GetSQLValueString($_POST['org'], "int"),
GetSQLValueString($_POST['prs'], "int"),
GetSQLValueString($_POST['cnt'], "int"),
GetSQLValueString($_POST['lng'], "int"),
GetSQLValueString($_POST['tot'], "int"),
GetSQLValueString($_POST['id'], "int"));
mysql_select_db($database_myconn, $myconn);
$Result1 = mysql_query($updateSQL, $myconn) or die(mysql_error());
}


It is actually updating the field 'tot' but not correctly. If I type: 5, 5, 5, 5, 5 into the update form then hit submit: the onscreen total shows 25. No problem!! If I check the MYSQL database all the individual values have updated but not the total. So I type 5, 5, 5, 5, 6 and hit submit. Again onscreen shows the correct value and all of the individual values update in the DB, including the total but it shows as 25 NOT 26. If I hit submit one more time it updates tot to 26.

After checking it seems as though what I want to do won't work...so I turned to Javascript and it works!! I am aware of the obvious drawbacks of using Javascript, but for what I need it does the job. Script below:
php
<?php require_once('Connections/myconn.php'); ?>
<?php
$currentPage = $HTTP_SERVER_VARS["PHP_SELF"];

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}

$editFormAction = $HTTP_SERVER_VARS['PHP_SELF'];
if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$editFormAction .= "?" . $HTTP_SERVER_VARS['QUERY_STRING'];
}

if ((isset($HTTP_POST_VARS["MM_update"])) && ($HTTP_POST_VARS["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE results SET name=%s, pro=%s, org=%s, prs=%s, cnt=%s, lng=%s, tot=%s WHERE id=%s",
GetSQLValueString($HTTP_POST_VARS['name'], "text"),
GetSQLValueString($HTTP_POST_VARS['pro'], "int"),
GetSQLValueString($HTTP_POST_VARS['org'], "int"),
GetSQLValueString($HTTP_POST_VARS['prs'], "int"),
GetSQLValueString($HTTP_POST_VARS['cnt'], "int"),
GetSQLValueString($HTTP_POST_VARS['lng'], "int"),
GetSQLValueString($HTTP_POST_VARS['tot'], "int"),
GetSQLValueString($HTTP_POST_VARS['id'], "int"));

mysql_select_db($database_myconn, $myconn);
$Result1 = mysql_query($updateSQL, $myconn) or die(mysql_error());
}

$maxRows_rs = 1;
$pageNum_rs = 0;
if (isset($HTTP_GET_VARS['pageNum_rs'])) {
$pageNum_rs = $HTTP_GET_VARS['pageNum_rs'];
}
$startRow_rs = $pageNum_rs * $maxRows_rs;

mysql_select_db($database_myconn, $myconn);
$query_rs = "SELECT * FROM results";
$query_limit_rs = sprintf("%s LIMIT %d, %d", $query_rs, $startRow_rs, $maxRows_rs);
$rs = mysql_query($query_limit_rs, $myconn) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);

if (isset($HTTP_GET_VARS['totalRows_rs'])) {
$totalRows_rs = $HTTP_GET_VARS['totalRows_rs'];
} else {
$all_rs = mysql_query($query_rs);
$totalRows_rs = mysql_num_rows($all_rs);
}
$totalPages_rs = ceil($totalRows_rs/$maxRows_rs)-1;

$queryString_rs = "";
if (!empty($HTTP_SERVER_VARS['QUERY_STRING'])) {
$params = explode("&", $HTTP_SERVER_VARS['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_rs") == false &&
stristr($param, "totalRows_rs") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_rs = "&" . implode("&", $newParams);
}
}
$queryString_rs = sprintf("&totalRows_rs=%d%s", $totalRows_rs, $queryString_rs);
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getGradeTotal() {
var ipro = document.form1.pro.value;
var iorg = document.form1.org.value;
var iprs = document.form1.prs.value;
var icnt = document.form1.cnt.value;
var ilng = document.form1.lng.value;
var itot = parseInt(ipro)+parseInt(iorg)+parseInt(iprs)+parseInt(icnt)+parseInt(ilng);
document.getElementById('tot').value = itot;
}
</script>
</head>

<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Id:</td>
<td><?php echo $row_rs['id']; ?></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Name:</td>
<td><input type="hidden" name="name" value="<?php echo $row_rs['name']; ?>" size="32">
<?php echo $row_rs['name']; ?> </td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Pro:</td>
<td><input name="pro" type="text" id="pro" onchange="getGradeTotal()" value="<?php echo $row_rs['pro']; ?>" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Org:</td>
<td><input name="org" type="text" id="org" onchange="getGradeTotal()" value="<?php echo $row_rs['org']; ?>" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Prs:</td>
<td><input name="prs" type="text" id="prs" onchange="getGradeTotal()" value="<?php echo $row_rs['prs']; ?>" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Cnt:</td>
<td><input name="cnt" type="text" id="cnt" onchange="getGradeTotal()" value="<?php echo $row_rs['cnt']; ?>" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Lng:</td>
<td><input name="lng" type="text" id="lng" onchange="getGradeTotal()" value="<?php echo $row_rs['lng']; ?>" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Tot:</td>
<td><input type="text" name="tot" id="tot" value="<?php echo $row_rs['tot']; ?>" readonly="true" size="32">
</td>
</tr>
<tr valign="baseline">
<td nowrap align="right"> </td>
<td><input type="submit" value="Update Record">
</td>
</tr>
</table>
<input type="hidden" name="MM_update" value="form1">
<input type="hidden" name="id" value="<?php echo $row_rs['id']; ?>">
</form>
<p> 
<table border="0" width="50%" align="center">
<tr>
<td width="23%" align="center">
<?php if ($pageNum_rs > 0) { // Show if not first page ?>
<a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, 0, $queryString_rs); ?>">First</a>
<?php } // Show if not first page ?>
</td>
<td width="31%" align="center">
<?php if ($pageNum_rs > 0) { // Show if not first page ?>
<a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, max(0, $pageNum_rs - 1), $queryString_rs); ?>">Previous</a>
<?php } // Show if not first page ?>
</td>
<td width="23%" align="center">
<?php if ($pageNum_rs < $totalPages_rs) { // Show if not last page ?>
<a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, min($totalPages_rs, $pageNum_rs + 1), $queryString_rs); ?>">Next</a>
<?php } // Show if not last page ?>
</td>
<td width="23%" align="center">
<?php if ($pageNum_rs < $totalPages_rs) { // Show if not last page ?>
<a href="<?php printf("%s?pageNum_rs=%d%s", $currentPage, $totalPages_rs, $queryString_rs); ?>">Last</a>
<?php } // Show if not last page ?>
</td>
</tr>
</table>
</p>
</body>
</html>
<?php
mysql_free_result($rs);
?>

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/3/08 12:17AM

Live PHP Help!

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month