How to insert data into DB which would be altered by selected number

Another date calculation related question - how to insert data into DB which would be altered by selected number?

In my case, if adding record you pick option 3 (which is basically 3 months interval) - add it to other date (i.e. date of purchase) and record final result? Would it be something to do with the following line?

GetSQLValueString($_POST['nextmaint'], "date"),
  1. As the function is not built-in, you are the owner of it and you are responsible for the implementation, in consequence that means the function does whatever you want it to do, and you are the only one that knows what it’s meant for, because nobody else has the code.

  2. Adding an interval to a date results in a date, so whatever you are doing with the first date you can do with the second one.

  3. Whatever method you chose to store the initial date - or any other date - you can use for the second date, too. If you are unsure about how to store dates, refer to the manual of your DBMS and i recommend to use PDO.

I think you missed the point that I have asked a question and looking for answer, not some thoughts and opinions, please.

To make it more simple, I have:
Date1 which is todays date i.e. 2018-07-03
I want to add Maintint which is i.e. 3 months

Result should be 2018-10-03.

Please note Maintint is being selected at the same page during the same process. Can some one give me straight answer, please?

The way I read it,

was a “straight answer”.

How do your versions of each compare and what isn’t working with the second?

try {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $pdo = new PDO('mysql:host=localhost;dbname=test', 'dbuser', 'dbpass');
        $stmt = $pdo->prepare('insert into maintenance (maintenance_date) values (?)');
        $stmt->execute([$_POST['maintenance_date']]);
        header('Location: ' . basename($_SERVER['SCRIPT_NAME']));
        exit;
    }

    $dt = new DateTime();
    $maintenanceDate1 = $dt->add(new DateInterval('P1M'))->format('Y-m-d');
    $maintenanceDate2 = $dt->add(new DateInterval('P1M'))->format('Y-m-d');
    $maintenanceDate3 = $dt->add(new DateInterval('P1M'))->format('Y-m-d');
    
} catch (Exception $e) {
    exit($e->getMessage());
}
?>
<html>
<head><title></title></head>
    <body>
        <form action="<?=basename($_SERVER['SCRIPT_NAME']);?>" method="POST">
            <label for="mdate">Select maintenance date:</label>
            <select id="mdate" name="maintenance_date">
            <option value="<?=$maintenanceDate1; ?>"><?=$maintenanceDate1; ?></option>
            <option value="<?=$maintenanceDate2; ?>"><?=$maintenanceDate2; ?></option>
            <option value="<?=$maintenanceDate3; ?>"><?=$maintenanceDate3; ?></option>
            </select>
            <input type="submit" value="Save">
        </form>
    </body>
</html>

That’s more like it but my code is quite a bit different and generally based on php 5.4 or so.

What I am trying to achieve is when you’re adding item, the nextmaint being calculated at the point when you submit the form. So there is no data in the db as you are creating new record. Does it make clearer?

Here’s the Add item page code

<?php require_once('Connections/eam.php'); ?>
<?php

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

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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 = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO assets_hardware (
						asset_type, 
						vendor, 
						model, 
						wsltoolno, 
						location, 
						date_purchase, 
						status, 
						user, 
						training, 
						maintenanceint, 
						comments, 
						monitor_size, 
						warranty, 
						subjecttoPAT, 
						spareparts, 
						addeddate, 
						manufacturerpn, 
						purchase_order, 
						lastmaint,
						nextmaint,
						maint1,
						maint2,
						maint3,
						maint4,
						maint5,
						maint6,
						maint7,
						maint8,
						maint9,
						maint10,
						serial) 						
						VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
						GetSQLValueString($_POST['assets_hardware_type'], "text"),
                       GetSQLValueString($_POST['vendor'], "text"),
                       GetSQLValueString($_POST['model'], "text"),
                       GetSQLValueString($_POST['wsltoolno'], "text"),
                       GetSQLValueString($_POST['location'], "text"),
                       GetSQLValueString($_POST['date_purchase'], "date"),
                       GetSQLValueString($_POST['status'], "text"),
                       GetSQLValueString($_POST['user'], "text"),
                       GetSQLValueString($_POST['training'], "text"),
                       GetSQLValueString($_POST['maintenanceint'], "text"),
                       GetSQLValueString($_POST['comments'], "text"),
                       GetSQLValueString($_POST['monitor_size'], "int"),
                       GetSQLValueString($_POST['warranty'], "text"),
                       GetSQLValueString($_POST['subjecttoPAT'], "text"),
                       GetSQLValueString($_POST['spareparts'], "text"),
                       GetSQLValueString($_POST['addeddate'], "text"),
                       GetSQLValueString($_POST['manufacturerpn'], "text"),
                       GetSQLValueString($_POST['purchase_order'], "text"),
					   GetSQLValueString($_POST['date_purchase'], "date"),
					   GetSQLValueString($_POST['nextmaint'], "date"),
					   GetSQLValueString($_POST['maint1'], "text"),
					   GetSQLValueString($_POST['maint2'], "text"),
					   GetSQLValueString($_POST['maint3'], "text"),
					   GetSQLValueString($_POST['maint4'], "text"),
					   GetSQLValueString($_POST['maint5'], "text"),
					   GetSQLValueString($_POST['maint6'], "text"),
					   GetSQLValueString($_POST['maint7'], "text"),
					   GetSQLValueString($_POST['maint8'], "text"),
					   GetSQLValueString($_POST['maint9'], "text"),
					   GetSQLValueString($_POST['maint10'], "text"),
					   GetSQLValueString($_POST['serial'], "text")
					   );

  mysql_select_db($database_eam, $eam);
  $Result1 = mysql_query($insertSQL, $eam) or die(mysql_error());

  $insertGoTo = "HardwareList.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_eam, $eam);
$query_rsVendors = "SELECT * FROM vendors ORDER BY vendor ASC";
$rsVendors = mysql_query($query_rsVendors, $eam) or die(mysql_error());
$row_rsVendors = mysql_fetch_assoc($rsVendors);
$totalRows_rsVendors = mysql_num_rows($rsVendors);

mysql_select_db($database_eam, $eam);
$query_rsPlatform = "SELECT * FROM assets_hardware_platform ORDER BY platform ASC";
$rsPlatform = mysql_query($query_rsPlatform, $eam) or die(mysql_error());
$row_rsPlatform = mysql_fetch_assoc($rsPlatform);
$totalRows_rsPlatform = mysql_num_rows($rsPlatform);

mysql_select_db($database_eam, $eam);
$query_rsHardwareType = "SELECT * FROM assets_hardware_type";
$rsHardwareType = mysql_query($query_rsHardwareType, $eam) or die(mysql_error());
$row_rsHardwareType = mysql_fetch_assoc($rsHardwareType);
$totalRows_rsHardwareType = mysql_num_rows($rsHardwareType);

mysql_select_db($database_eam, $eam);
$query_rsDivision = "SELECT * FROM division ORDER BY division ASC";
$rsDivision = mysql_query($query_rsDivision, $eam) or die(mysql_error());
$row_rsDivision = mysql_fetch_assoc($rsDivision);
$totalRows_rsDivision = mysql_num_rows($rsDivision);

mysql_select_db($database_eam, $eam);
$query_rscube = "SELECT * FROM cube ORDER BY cube ASC";
$rscube = mysql_query($query_rscube, $eam) or die(mysql_error());
$row_rscube = mysql_fetch_assoc($rscube);
$totalRows_rscube = mysql_num_rows($rscube);

mysql_select_db($database_eam, $eam);
$query_rsLocation = "SELECT * FROM location ORDER BY location ASC";
$rsLocation = mysql_query($query_rsLocation, $eam) or die(mysql_error());
$row_rsLocation = mysql_fetch_assoc($rsLocation);
$totalRows_rsLocation = mysql_num_rows($rsLocation);

mysql_select_db($database_eam, $eam);
$query_rsHardwareStatus = "SELECT * FROM assets_hardware_status ORDER BY assets_hardware_status ASC";
$rsHardwareStatus = mysql_query($query_rsHardwareStatus, $eam) or die(mysql_error());
$row_rsHardwareStatus = mysql_fetch_assoc($rsHardwareStatus);
$totalRows_rsHardwareStatus = mysql_num_rows($rsHardwareStatus);

mysql_select_db($database_eam, $eam);
$query_rsMonitorSize = "SELECT * FROM assets_hardware_monitor_size";
$rsMonitorSize = mysql_query($query_rsMonitorSize, $eam) or die(mysql_error());
$row_rsMonitorSize = mysql_fetch_assoc($rsMonitorSize);
$totalRows_rsMonitorSize = mysql_num_rows($rsMonitorSize);
?>




<meta name='viewport' content='width=500, initial-scale=1.5, maximum-scale=2.0, user-scalable=0'>
<?php $pageTitle="Add Asset"; ?>
<?php include('includes/header.php'); ?>
    
         
			
      
	
      <fieldset>
      <legend> Add Asset	  <i class="fa fa-print fa-lg" aria-hidden="true" onclick="goPrint()" onmouseover="" style="cursor: pointer;float:right;" ></i> 
	  <i class="fa fa-home fa-lg" aria-hidden="true" onclick="location.href='index.php';" onmouseover="" style="cursor: pointer;float:right;">&ensp;</i>
	  <i class="fa fa-arrow-circle-left fa-lg" aria-hidden="true" onclick="goBack()" onmouseover="" style="cursor: pointer;float:right;">&ensp;</i>	</legend>

	<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
      
      $expensions= array("jpeg","jpg","png","gif");
      
      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 3097152) {
         $errors[]='File size must be no more than 2.95 MB';
      }
      
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"pictures/".$file_name);
      }else{
         print_r($errors);
      }
   }
?>
	  <p>
	  <label for="File">Select picture:</label>
	 <form action = "" method = "POST" enctype = "multipart/form-data">
	  <input type = "file" name = "image" />
	 <input type = "submit" value="Upload" />	
         <ul>
         <?php echo $_FILES['image']['name']; ?>
		 <?php if(empty($_FILES)==false) { echo "<font color='green'><STRONG>HAS BEEN UPLOADED</STRONG></font>"; } ?>
         </ul>
		 </form>
	  </p>
<form action="<?php echo $editFormAction; ?>" method="post" name="form1">
      <p><label for="Platform">Asset Type: </label><select name="assets_hardware_type" required>
        <option value="">-</option>
        <?php
do {  
?>
        <option value="<?php echo $row_rsHardwareType['assets_hardware_type']?>"><?php echo $row_rsHardwareType['assets_hardware_type']?></option>
        <?php
} while ($row_rsHardwareType = mysql_fetch_assoc($rsHardwareType));
  $rows = mysql_num_rows($rsHardwareType);
  if($rows > 0) {
      mysql_data_seek($rsHardwareType, 0);
	  $row_rsHardwareType = mysql_fetch_assoc($rsHardwareType);
  }
?>
      </select> </p>
	  <p>
        <label for="Platform">Maintenance Interval</label>
        <select name="maintenanceint" required>
          <option value=""> - </option>
          <?php
			do {  
			?>
          <option value="<?php echo $row_rsPlatform['platform']?>"><?php echo $row_rsPlatform['platform']?></option>
          <?php
			} while ($row_rsPlatform = mysql_fetch_assoc($rsPlatform));
			  $rows = mysql_num_rows($rsPlatform);
			  if($rows > 0) {
				  mysql_data_seek($rsPlatform, 0);
				  $row_rsPlatform = mysql_fetch_assoc($rsPlatform);
			  }
			?>
        </select>
		<span class="tiny">Months</span>
      </p>
      <p>
        <label for="Vendor">Make</label>
        <select name="vendor" required>
          <option value=""> - </option>
          <?php
do {  
?>
          <option value="<?php echo $row_rsVendors['vendor']?>"><?php echo $row_rsVendors['vendor']?></option>
          <?php
} while ($row_rsVendors = mysql_fetch_assoc($rsVendors));
  $rows = mysql_num_rows($rsVendors);
  if($rows > 0) {
      mysql_data_seek($rsVendors, 0);
	  $row_rsVendors = mysql_fetch_assoc($rsVendors);
  }
?>
        </select>
      </p>
      <p>
        <label for="Model">Model</label>
        <input name="model" type="text" size="20" maxlength="30" autocomplete="off" required />
      </p>
      <p>
        <label for="Asset Tag">Serial Number</label>
        <input name="serial" type="text" size="20" maxlength="40" autocomplete="off" />
      </p>
	  
	  <p>
        <label for="Serial Number">WSL Tool Number</label>
        <input name="wsltoolno" type="text" size="20" maxlength="30" autocomplete="off" required />
      </p>
      <p>
        <label for="Asset Tag">Manufacturer P/N</label>
        <input name="manufacturerpn" type="text" size="20" maxlength="30" autocomplete="off" required />
      </p>
      <p>
        <label for="Purchase Order">Purchase Order</label>
        <input name="purchase_order" type="text" size="20" maxlength="30" autocomplete="off" required />
      </p>        
      <hr />
      <p>
        <label for="Date Purchased">Date Purchased</label>
        <input type="text" name="date_purchase" value="" size="8" autocomplete="off" required />
        <img src='images/scw.gif' title='Click Here' alt='Click Here' onclick="cal.select(document.forms['form1'].date_purchase,'anchor2','yyyy-MM-dd'); return false;" name="anchor2" id="anchor2" style="cursor:hand" /> </p>
      <p>
        <label for="Warranty Date">Warranty Date</label>
        <input type="text" name="warranty" value="" size="8" autocomplete="off" required />
        <img src='images/scw.gif' title='Click Here' alt='Click Here' onclick="cal.select(document.forms['form1'].warranty,'anchor1','yyyy-MM-dd'); return false;"
   name="anchor1" id="anchor1" style="cursor:hand" /></p>
      <p>
        <label for="Status">Status</label>
        <select name="status" required>
          <option value=""> - </option>
          <?php
			do {  
			?>
          <option value="<?php echo $row_rsHardwareStatus['assets_hardware_status']?>"><?php echo $row_rsHardwareStatus['assets_hardware_status']?></option>
          <?php
			} while ($row_rsHardwareStatus = mysql_fetch_assoc($rsHardwareStatus));
			  $rows = mysql_num_rows($rsHardwareStatus);
			  if($rows > 0) {
				  mysql_data_seek($rsHardwareStatus, 0);
				  $row_rsHardwareStatus = mysql_fetch_assoc($rsHardwareStatus);
			  }
			?>
        </select>
      </p>
 <hr />	  
      <p>
      <label for="User">Added By</label>
        <input name="user" type="text" size="20" value="<?php echo $_SESSION['MM_Username'];?>" STYLE="background-color: #F2EFE9;" readonly />
         </p>
		
		<p>
        <label for="User">Date Added</label>
        <input type="text" name="addeddate" value="<?php echo date('Y-m-d'); ?> " size="20" STYLE="background-color: #F2EFE9;" readonly>
        </p>
		
		
		<p>	  
        <label for="Division">Staff Training Req.?</label>
        <select name="training" required>
          <option value=""> - </option>
          <?php
			do {  
			?>
          <option value="<?php echo $row_rsDivision['division']?>"><?php echo $row_rsDivision['division']?></option>
          <?php
			} while ($row_rsDivision = mysql_fetch_assoc($rsDivision));
			  $rows = mysql_num_rows($rsDivision);
			  if($rows > 0) {
				  mysql_data_seek($rsDivision, 0);
				  $row_rsDivision = mysql_fetch_assoc($rsDivision);
			  }
			?>
        </select>
      </p>
      <p>
        <label for="Location">Location</label>
        <select name="location" required>
          <option value=""> - </option>
          <?php
			do {  
			?>
          <option value="<?php echo $row_rsLocation['location']?>"><?php echo $row_rsLocation['location']?></option>
          <?php
			} while ($row_rsLocation = mysql_fetch_assoc($rsLocation));
			  $rows = mysql_num_rows($rsLocation);
			  if($rows > 0) {
				  mysql_data_seek($rsLocation, 0);
				  $row_rsLocation = mysql_fetch_assoc($rsLocation);
			  }
			?>
        </select>
      </p>
  
	  <p>
        <label for="Comments">Subject to PAT test</label>
        <select name="subjecttoPAT" required>
          <option value=""> - </option>
          <?php
			do {  
			?>
          <option value="<?php echo $row_rscube['cube']?>"><?php echo $row_rscube['cube']?></option>
          <?php
			} while ($row_rscube = mysql_fetch_assoc($rscube));
			  $rows = mysql_num_rows($rscube);
			  if($rows > 0) {
				  mysql_data_seek($rscube, 0);
				  $row_rscube = mysql_fetch_assoc($rscube);
			  }
			?>
        </select>
      </p>
	 
	  <p>
        <label for="Comments">Supplier & Spares</label>
        <textarea name="spareparts" cols="32" rows="" wrap="virtual" ></textarea><span class="tiny"></span>      </p>
      <p>
        <label for="Comments">Comments</label>
        <textarea name="comments" cols="32"></textarea>
      </p>
	  
	  <hr />
	 <p> <center><h5>Maintenance Instructions</h5> </center></p> 
     <p>
	 <label for="maint1">Step 1</label>
	 <textarea name="maint1" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 
	  
     <p>
	 <label for="maint2">Step 2</label>
	 <textarea name="maint2" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint3">Step 3</label>
	 <textarea name="maint3" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint4">Step 4</label>
	 <textarea name="maint4" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint5">Step 5</label>
	 <textarea name="maint5" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint6">Step 6</label>
	 <textarea name="maint6" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint7">Step 7</label>
	 <textarea name="maint7" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint8">Step 8</label>
	 <textarea name="maint8" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint9">Step 9</label>
	 <textarea name="maint9" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
     <p>
	 <label for="maint10">Step 10</label>
	 <textarea name="maint10" type="text" cols="32"  maxlength="250" ></textarea>
	 </p> 	  
	  
	  
	  
     <center> <p class="submit">
        <input type="submit" value="Add" name="submit" />
      </p></center>
	  

  
	 
      <input type="hidden" name="MM_insert" value="form1" />
	

      </fieldset>
	  
    </form>
<?php include('includes/footer.php'); ?>
<?php
mysql_free_result($rsVendors);
mysql_free_result($rsPlatform);
mysql_free_result($rsHardwareType);
mysql_free_result($rsDivision);
mysql_free_result($rsLocation);
mysql_free_result($rsHardwareStatus);
mysql_free_result($rsMonitorSize);
?>


 

I’m sorry to say that what I think you mean by this is “I am looking for someone to write all the code for me so I don’t have to do it myself”. And then when someone does, @TenDolla again, you want it changing so you can copy-and-paste it directly into your code.

Between the content of your other thread where calculating the next maintenance date was discussed in detail, and exact code (eventually) provided, and this extra code in post #5, can you not assemble enough to have a stab at writing the code yourself?

All you need to do is change this line in your code:

GetSQLValueString($_POST['nextmaint'], "date"),

so that instead of using the $_POST variable directly, you get the current date, calculate the value based on the maintenanceint selection from the form, and use the result. And while that might be unfamiliar to you, it’s all code that you have been given in this thread or the other one.

I’m surprised you don’t get errors on that line above, as I can’t see a form variable anywhere with that name.

1 Like

You are right - if someone cannot explain in easy way, I simply ask for exact code (to save time). If you had a look in the other threads you should see some people CAN give advise which results in actually compiling a working code. It’s just like good and bad teacher. When it’s bad, you just want it to work. We all did that in school or other education level. That’s the nature of us.

And second half of your post actually gives me useful info. If you would read thread no one mentioned anything about using calculated values instead of &_POST. I didn’t knew I can do that - now I do.

The bit I am struggling is how and at which point I can pick up i.e. what Interval has been selected, I have tried many ways and some samples from web but no luck.

Edit: Can you do calculations inside GetSQLValueString()?

You can see how you get the data from the $_POST variables when you are inserting it into the query string, it’s just the same. Assign the value of the maintenance period to a variable, then use (probably) switch() to decide how many actual days that is (unless your ‘value’ already has that). You can then apply it to the current date (or maintenance start date, if you have one) and there’s your value to insert.

No idea, sorry, I don’t know where that function comes from. But you’re better off (IMO) doing the calculation first so all you have is a single variable to insert.

It’s actually recommended practice - you should never insert values from a form directly into a query, because they could be corrupted or worse. You should always sanitise any value that’s come from a user. Now, maybe your GetSQLValueString() is doing some kind of sanitising, I don’t know.

Hmm, sort of. I can’t ever remember being in school, not understanding what the teacher was telling me (regardless of whether the teacher was bad or whether it was my fault) and just sitting back and having them do it for me. But then, I don’t think of a forum as a teacher / pupil situation - I certainly don’t think of myself as a teacher, more of a pupil that might be sharing notes. But not doing the other guys homework for him.

So, your steps are:

  1. Get the value of the maintenance duration selected
  2. Convert that into a number of days, if you have to
  3. Create a date based on the start date (today?) and that number of days
  4. Put it into the query
  5. Stop using mysql_ functions and use prepared statements

Some might say the last should be the first. Steps 1-3 have already been covered in detail, step 4 is just a case of changing the variable you insert.

My code was a sample just to show how you can play around with the dates. It may or may not work as it is directly for OP’s purpose but the point was to give some tools for achieving what the OP wants to achieve.

1 Like

My sample code should work also on PHP 5.4. DateTime works in PHP 5.2 → and DateTime->add() method works in PHP 5.3 →

Slightly off topic - because I’ve pasted entire page code, how and where I can pick up ID number (which is auto-increase within DB)? I have added feature to upload picture and want to rename it to match the ID, so it’s easier to pick up correct picture when looking at item’s details.
EDIT: I now have this code:

mysql_select_db($database_eam, $eam);
$lastid = "SELECT * FROM assets_hardware WHERE id = LAST_INSERT_ID()";

But it doesn’t seem to work, what’s wrong?

Now relating to topic - How do I get value of what maintenance selection was selected? If I use $row_rsHardwareAsset['maintenanceint']; will it work on the same page? Going to try it out but If someone has quick answer let me know. Thank you.

By looking at the value in the $_POST array. The entry for that input field will be the value from the value= portion of your <option>, or the display value if you did not specify a value. (ETA - looking at the code above, you do specify a value, but it’s the same as the display for each option, so that part is redundant).

That’s the data from your query, not the item that the user selected.

I know how to do it in PDO, but I don’t know how to do it in the old no-longer-part-of-PHP mysql calls. In PDO, it needs to be done immediately after the query to insert the new row. One easy way to do it would be to run another query:

SELECT id FROM assets_hardware ORDER BY id DESC LIMIT 1

which would just return the largest value of the id field.

Actually no. That is prone to race conditions where user A and B both insert a new record at the same time and both end up with the same ID being fetched by that query (namely the ID of the last inserted record by either A or B). Now in smaller sites this might not happen, but on a larger scale it most definitely will.

What you should do instead is use PDOs lastInsertId method, which will give back the last inserted ID for the current connection, instead of the last inserted ID overall.

For the OP, you would need to use mysql_insert_id.

Thanks for taking your time to think about it - I have found a solution. Instead of getting ID I use picture name (which is generated by camera so will never use the same name) and simply inserting this name into dedicated column. Then on Details page just using following code to get the right image;

<img class="resize" src='pictures/<?php echo $row_rsHardwareAsset['pictureid'];?>' />

Works fine so think will stick to it.

Now, back to question about picking up selection. How can I do this? As far as I understand only during submit action data will be picked up (the option you have selected for Maintint)?

Yes, good point. I’ve used the PDO that you mentioned, but not the old-style one.

1 Like

Warning: assumption

What if you format the SD card in the camera and start taking pictured again? I’m fairly certain it will start over from 0 again.

Unless of course you have a camera that uses the current date and time for photos. But then what happens when both cameras take picture in the exact same second?

See where I’m going with this?

Hm, I assume that pictures will only be taken by the same device (tablet in this case) so this shouldn’t be a big problem.

If there will be a concerns I will have to add script to rename the files to match ID or generate some sort of name codding.

Neither of my cameras do this, but what they do do, which would also cause an issue, is get to a “9999” suffix then start again at zero.

Better to deal with it now than have the issue later, when the system is running live, and have to fix it “RIGHT NOW” as you’ve got people sitting around waiting for it to be fixed. Design around it while you have the luxury of time to test the solution.

1 Like

I would do it now, If only knew how… :sweat_smile: I have put this down on my list but priority now is inserting modified date into DB and then creating email reminder…