Format array outputs in form serialize PHP - php

Im currently using the json_encode in converting array to strings
which outputs data in a straight pattern in my table
user
-----------
id | name
-------------------------------------------
1 |"name1","name2","name3","name4","name5"
But i want to have an output where the table data will look like this.
user
-----------
id | name
-----------
1 | name1
2 | name2
3 | name3
4 | name4
5 | name5
My PHP code
<?php
$connect = mysqli_connect("localhost", "root", "", "dbsample");
if(isset($_POST["check_val"])){
$check_val = htmlspecialchars(strip_tags("check_val"));
$number = json_encode($_POST["name"]);
for ($i = 0; $i < count($number); $i++) {
if ($number[$i] != "") {
$query = "INSERT INTO tbl_name(name) VALUES (?)";
$stmt = $connect->prepare($query);
$number[$i] = htmlspecialchars(strip_tags($number[$i]));
$stmt->bind_param("s", $number);
if($stmt->execute()) {
echo "SUCCESS";
# code...
}else
{
echo "ERROR";
}
}
else{
echo "Please Enter Name";
}
}
}
?>

Related

How to select and assign to a specific $key, a specific $value, among multiple choices?

I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}

How to do foreach loop through different variable in php

I have a dynamic form which have dynamic input of textbox and variable of date,float and time.I want to insert those input dynamically into my sql table.
So here is the part of my code.I'm only able to loop through one variable,When i want to loop through the time and float,it face the conversion problem on float and time.(If any picture needed just let me know )
$ct = 0;
if ($_POST['Dates'] && $_POST['slct']) {
foreach ($_POST['Dates'] as $value) {
$values = $value;
$dates = $_POST['Dates']; // for leave date
$datess = $_POST['datess']; // for created date
$Area = $_COOKIE['cooAreaCode'];
$days = $_POST['slct'];
$time = date("h:i a", strtotime($frtime));
$times = date("h:i a", strtotime($totime));
$frtime = $_POST['frtime'];
$totime = $_POST['totime'];
$link_mssql = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
$sql = "SELECT MAX(RefNo) as val from tblLeaveHeader";
$res = odbc_exec($link_mssql, $sql);
while (odbc_fetch_row($res)) {
$count = odbc_result($res, "val");
}
odbc_free_result($res);
$temp = sprintf('%08d', $count + 1);
if (empty($_POST['frtime']) && empty($_POST['totime'])) {
$sql3 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', NULL, NULL)";
$res = odbc_exec($link_mssql, $sql3);
$ct++;
} else {
$sql2 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', '$frtime[$ct]', '$totime[$ct]')";
$res = odbc_exec($link_mssql, $sql2);
$ct++;
}
}
}
Example of result in sql table
| ID | Refno | Leavetype | Leaveday | Leavdd |frtime|totime
| 1 | 00001 | Annual Leave | 1 | 2017-07-17 |3.00 | 7.00
| 2 | 00001 | Annual Leave | 1 | 2017-07-18 |4.00 | 6.00

MySQL Querying Duplicates

So, I have a database called teams, and it currently looks like this:
team_id | leader_id | student_id
1 | 123456 | 1234
2 | 1234 | 123456, 1234567890
3 | 1234 | 123456
4 | 0 | 12345, 1234, 1234567890
5 | 0 |
6 | 0 |
My students database looks like this
student_id | first_name | last_name
123456 | qwer | qwer
0 | asd | zxc
1234567890 | mmm |nnn
The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.
Example:
If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.
Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id
My PHP
<?php
error_reporting(0);
require '../../connect.php';
$leader_id = $_POST['leader_id'];
$student_id = array(
$_POST['student_id_1'],
$_POST['student_id_2'],
$_POST['student_id_3'],
$_POST['student_id_4'],
$_POST['student_id_5'],
$_POST['student_id_6']
);
$students_save = array();
if(!empty($leader_id)) {
foreach ($student_id as $id) {
if(!empty($id)) {
array_push($students_save, $id);
}
}
foreach ($students_save as $save) {
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");
if(mysqli_num_rows($check_id)>0) {
$students_save = implode(", ", $students_save);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
}
} else if(empty($leader_id)){
header("Location: ../../../admin.php?Please add you're input values");
}
?>
As you edited your question,
all you need is to break out of your foreach loop, if you $result is
successfull so add break in if($result) rest of the code will remain
the same
See the code below
<?php
foreach ($students_save as $save) {
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");
if(mysqli_num_rows($check_id)>0) {
$students_save = implode(", ", $students_save);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
break; // add break here, as if your condition
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
}
Try the below code if it helps,
<?php
error_reporting(0);
require '../../connect.php';
$leader_id = $_POST['leader_id'];
$student_id = array();
if(isset($_POST['student_id_1'])) $student_id[] = $_POST['student_id_1'];
if(isset($_POST['student_id_2'])) $student_id[] = $_POST['student_id_2'];
if(isset($_POST['student_id_3'])) $student_id[] = $_POST['student_id_3'];
if(isset($_POST['student_id_4'])) $student_id[] = $_POST['student_id_4'];
if(isset($_POST['student_id_5'])) $student_id[] = $_POST['student_id_5'];
if(isset($_POST['student_id_6'])) $student_id[] = $_POST['student_id_6'];
if(!empty($leader_id)) {
$students_save = implode(", ", $student_id);
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id IN ($students_save)");
if(mysqli_num_rows($check_id)>0) {
//$student_ids = array();
//while($row = $check_id->fetch_array(MYSQLI_ASSOC)) $student_ids[] = $row['student_id'];
//$students_save = implode(", ", $student_ids);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id) VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
} else if(empty($leader_id)) {
header("Location: ../../../admin.php?Please add you're input values");
}
?>
This code should help you.
Note: I have added comment to a part of the code. If you remove the commenting, then it will only insert the student_id which exists in the students table.

Using for() to update multiple rows in mysql database

I am trying to update multiple rows in a database. I have the total number of rows in my table counted and bound to a variable:
$result = '32'
I then attempt to query each row:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'];
$substrate_desc = $_POST['substrate_desc'];
$substrate_base = $_POST['substrate_base'];
$substrate_tax = $_POST['substrate_tax'];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
My problem is when I run this script, each row in the table is filled with the last row edited. For example:
AAA | Aaaaa | 1.00 | 6.35
BBB | Bbbbb | 2.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
Becomes:
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
How can I fix this script so it will update each row individually?
Try this:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'][$x];
$substrate_desc = $_POST['substrate_desc'][$x];
$substrate_base = $_POST['substrate_base'][$x];
$substrate_tax = $_POST['substrate_tax'][$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
I changed the "name" fields in my form to include the substrate's ID:
<input name="substrate_name_'.$substrate_id.'" />
Then did the same for the update query (where the id is defined by the loop, $x):
$substrate_name = $_POST['substrate_name_'.$x];
$substrate_desc = $_POST['substrate_desc_'.$x];
$substrate_base = $_POST['substrate_base_'.$x];
$substrate_tax = $_POST['substrate_tax_'.$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
And this gave me the desired result. Thanks to Rimon Khan for the idea and to everyone who commented.

Best way of getting a row result with out having to do several querys?

One of the fields coming from the db is separated by "," eg(1,2,3,4,5)
This is the code I'm using:
$result = mysqli_query($con, "SELECT * FROM login WHERE phone=$user");
while ($row = mysqli_fetch_array($result)) {
$friends = $row['friends'];
$data = $friends;
$arr = explode(',', $data);
$today = date("d F", strtotime($row['time']));
$hour = date('g:i',
strtotime($row['time']));
if ($today < $row['time']) {
$today;
} else {
$today = $hour;
};
for ($i = 0; $i < count($arr); $i++) {
$friend = array($data);
foreach($friend as $value) {
echo "
<div class='contacts_item sep_cont'>
<img class='user_img' src='".$row['picture']."'>
<div class='contacts_title'>".$arr[$i]."<div class='time'>".$today."</div></div>
<div>".$row['name']."</div> </div> ";
}
}
}
Any advice?
If I understand what you want I think you can create a table with only the relation between login and friends like
TABLE login_friends
id | login_id | friend_id |
1 | 1 | 2 |
2 | 1 | 3 |
3 | 2 | 3 |

Categories