I have a textarea which is going to be post to PHP.
In the PHP script, I will explode the textarea by newline.
Then, I will make a loop to iterate the array to check if the value already exist in the MySQL or not. If it already exist, then I will do a continue, else I will do an insert.
This is how my code looks like:
$route = $_POST['gatewayvalue'];
$account_number = $_POST['account_number'];
$route = strtoupper($route);
$routelist = explode("\n", $route);
$count = count($routelist);
$invalid = 0;
for($i=0;$i<$count;$i++){
if(preg_match("/000F26/i", $routelist[$i])){
$routeinsert = str_replace("000F26", "", $routelist[$i]);
$verify = "SELECT route FROM gw_gateway WHERE route='$routeinsert'";
$result = mysql_query($verify);
$row = mysql_fetch_array($result);
$checkroute = $row['route'];
if($checkroute == $routeinsert){
$validate = false;
$invalid++;
continue;
}
else{
$validate = true;
}
}
else{
$routeinsert = $routelist[$i];
$verify = "SELECT route FROM gw_gateway WHERE route='$routeinsert'";
$result = mysql_query($verify);
$row = mysql_fetch_array($result);
$checkroute = $row['route'];
if($checkroute == $routeinsert){
$validate = false;
$invalid++;
continue;
}
else{
$validate = true;
}
}
if($validate == true){
$updateroutesql = "INSERT INTO gw_gateway SET route='$routeinsert', gw_reseller1='$account_number'";
$updateroutesqlres=mysql_query($updateroutesql) or die("Can not perform update query !".mysql_error());
}
}
However, when I insert 2 similar values, for example, 030301 twice in the textarea.
The 1st value will be rejected, but the 2nd value will be inserted as an empty value.
My table has 3 fields.
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| route | varchar(20) | NO | PRI | | |
| account_number | varchar(20) | YES | | NULL | |
| gw_reseller1 | varchar(45) | YES | | NULL | |
+----------------+-------------+------+-----+---------+-------+
And this is what happened when I try to insert 2 similar values
+----------+----------------+--------------+
| route | account_number | gw_reseller1 |
+----------+----------------+--------------+
| 030302 | NULL | NULL |
| NULL | 201-000001 | |
| 030301 | NULL | 201-000001 |
+----------+----------------+--------------+
First of all, try to shorten Your code. You have the same code parts twice which is useless…
Then, sanitize Your input.
Finaly, move on with
PDOor at leastmysqli_*functions asmysql_*is deprecated now.New code:
Try this edited code – should be OK. If there is still some value inserted as null or empty it means that You have typed an empty line in the textarea and You should also check for the route not to be empty when inserting…