Using preg_match on array from POST checkbox values - php

The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?

It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);

You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>

Related

SQL - Why I have a duplicated row if im checking that unique id exists?

I found a duplicated row in my table
> image from my table
But in my code, I check if "unique_id" key exists, then update this row, else, create..
I am very noob with sql and I made some functions to make more easy my life... this is my "send_score.php" file
<?php
header('Content-Type: text/plain');
header("Access-Control-Allow-Origin: *");
include "../../functions.php";
$servername = "xxx";
$database = "xxx";
$username = "xxx";
$password = "xxx";
$tabla = "xxx";
$unique_key = $_POST['unique_key'];
$nick = $_POST['nick'];
$puntos = $_POST['puntos'];
$con = sql_connect($servername, $username, $password, $database);
if ( sql_check_row($con,$tabla,"unique_key","'".$unique_key."'") ) {
//if exists, replace
if ( sql_update_row($con,$tabla,"nick",$nick,"unique_key",$unique_key) && sql_update_row($con,$tabla,"sc",$puntos,"unique_key",$unique_key) ) {
echo "OK UPDATE";
exit;
}
else {
echo "BAD UPDATE";
exit;
}
}
else {
//if not exists, create
$arr_key = array("unique_key","nick","sc");
$arr_val = array("'".$unique_key."'","'".$nick."'",$puntos);
if ( sql_insert_row($con,$tabla,$arr_key,$arr_val) ) {
echo "OK INSERT";
exit;
}
else {
echo "BAD INSERT";
exit;
}
}
sql_close($con);
?>
and here is the functions that im using here
function sql_connect($servername, $username, $password, $database) {
return mysqli_connect($servername, $username, $password, $database);
}
function sql_close($con) {
return mysql_close($con);
}
function sql_check_row($con,$table,$key,$value) {
$sql = mysqli_query($con, "SELECT * FROM ".$table." WHERE ".$key." = ".$value);
if( mysqli_num_rows($sql) ) {
return true;
}
else {
return false;
}
}
function sql_update_row($con,$table,$key_set,$value_set,$key_where,$value_where) {
$sql = mysqli_query($con,"UPDATE ".$table." SET ".$key_set." = '".$value_set."' WHERE ".$key_where." = '".$value_where."';");
if ($sql) {
return true;
}
else {
return false;
}
}
function sql_insert_row($con,$table,$key_arr,$value_arr) {
$keys = "(";
for ( $i = 0; $i < sizeof($key_arr); $i++ ){
if ($i != 0) {
$keys .= ",";
}
$keys .= $key_arr[$i];
}
$keys .= ")";
$query = "INSERT INTO ".$table." ".$keys." VALUES (";
for ( $i = 0; $i < sizeof($value_arr); $i++ ){
if ($i != 0) {
$query .= ",";
}
$query .= $value_arr[$i];
}
$query .= ");";
$sql = mysqli_query($con,$query);
if ($sql) {
return true;
}
else {
return false;
}
}
According to me, it shouldn't create a new row because a row already exists with the same "unique_id" and in the image, both rows have exactly the same "unique_id"... why???
A simply strategy here is to write the values of column "unique_key"
in an array and then test if the new value exist with "in_array()".
If the value exists you update. If not you insert a new row:
<?php
$all_unique_ids = array();
$con = sql_connect($servername, $username, $password, $database);
$stmt = $con->prepare("SELECT `unique_key` FROM `".$tabla."`");
$stmt->execute();
foreach ($stmt->get_result() as $row)
{
$all_unique_ids[] = $row['unique_key'];
}
mysqli_close($con);
if(in_array($unique_id, $all_unique_ids))
{
sql_update_row(.....);
}
else
{
sql_insert_row( ......);
}
?>
Your code has a race condition. Two requests to the same page at the same time with the same unique_id will check the database at the same time and both get back the same result. Namely that the given unique_id is not in the database.
Both requests will then each INSERT a row with the same unique_id. This is why databases allow you to give a column a unique constraint.

Data not insert into database

I'm making a form for some project. The problem is when the user enter their data using the field and then submit, the input not keep in the database.
Also when clicking submit the direct page show blank empty page even the connection test also not showing.
I'm using almost similar code for other project and it work except for this.
below is my code:
<?php
//check connection
require 'config.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//asas (table name)
$id = $_POST["Sid"]; $ic = $_POST["Sic"];
$name = $_POST["Snp"]; $jant = $_POST["J1"];
$trum = $_POST["Chr"];$tbim = $_POST["Chp"];
$mel = $_POST["Sem"]; $arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"]; $uni = $_POST["Sis"];
$bid = $_POST["tpe"];$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];$bik = $_POST["B1"];
$tem = $_POST["te"];$mula = $_POST["tm"];
$tamm = $_POST["tt"]; $res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];$keb = $_POST["fileToUpload3"];
$link = mysqli_connect($h,$u,$p,$db);
if('id' != '$Sid'){
$asas = "insert into asas Values ('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values ('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
mysqli_query($link,$asas);
mysqli_query($link,$inst);
mysqli_query($link,$indr);
mysqli_close($link);
}
else
{
echo "failed"
}
?>
<b>Register complete</b>
Can anybody tell me what the error or maybe some solution. Thanks
I think you are having problem in insert query, please check this:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
Write this kind.
thank you
there are few issues with the code like variable id was used without $
and need to use die method with mysqli_query() function to check for
errors, please check below improved codes, it may help you -
<?php
//check connection
require 'config.php';
if (isset($_POST)) {
//asas (table name)
$id = $_POST["Sid"];
$ic = $_POST["Sic"];
$name = $_POST["Snp"];
$jant = $_POST["J1"];
$trum = $_POST["Chr"];
$tbim = $_POST["Chp"];
$mel = $_POST["Sem"];
$arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"];
$uni = $_POST["Sis"];
$bid = $_POST["tpe"];
$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];
$bik = $_POST["B1"];
$tem = $_POST["te"];
$mula = $_POST["tm"];
$tamm = $_POST["tt"];
$res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];
$keb = $_POST["fileToUpload3"];
}
$link = mysqli_connect($h, $u, $p, $db);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
// if('id' != '$Sid'){
if ($id != '$Sid') {
$asas = "insert into asas Values
('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values
('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
if (mysqli_query($link, $asas)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $inst)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $indr)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
}
mysqli_close($link);
?>
<b>Register complete</b>
just use or die after mysqli_query
mysqli_query($link,$asas)or die ('Unable to execute query. '. mysqli_error($link));
you will get to know what is the actual problem

PHP - Insert Value with Key from another array into Array in Specific Place

I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!

null value when i opened the php script in IE

I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?

Undefined variable while fetching data from mysqli

I'm new to php n I'm trying to make a phone to timezone converter.
I'm getting the error undefined variable '$result' on line 49
How do I resolve it.
Also if you can find out any other mistakes I've made
Please chck for errors I'm making
Phone number:
<button type="submit" name="submit" action="submit">
Submit
</button>
</form>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$ccode=$_POST["phone"];
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$pattern = '/^\(?[\d]{1,4}\)?( |-)?/';
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else $code = substr($ccode, 0, 4);
$q = "SELECT nicename FROM country.country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($record);
if (empty($_POST["phone"]))
{
echo "<p>Please write a Phone Number!</p>";
}
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = " . $record['nicename'];
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($result);
?>
</body>
Thanks for the help!
I believe this way it will works. I'm not sure about $code, if he contains the right information, you can check that by echo'ing the $code.
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else { $code = substr($ccode, 0, 4); }
$q = "SELECT nicename FROM country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
echo '<pre>';
print_r($record);
} else { echo "<br/>NO RECORD"; }
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = '" . $record['nicename'] . "'";
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
echo '<pre>';
print_r($result);
//Here $result will exist!
} else { echo "<br/>NO RECORD"; }
// You had your $result here, and here, the result may not exist,
// depending if the query succeeded or not.
// Same counts for the query above.
There were 2 problems as far as I can tell.
1 was that you tried to print $record, while $record may not have existed, and the same counts for $result.
2 was the zone-query, if you check if a column/field equals a certain string, then make sure the string has quotes around itself. So country_name='something'. You didn't have these quotes around $record['nicename'], so whatever came out of $record['nicename'], he thought it was a column/field, but not a value to check upon.

Categories