I'm using Laravel 8 framework.
Using a query to get values from the table in and display it in the checkbox, but when I select more than one it just displays single, not multiple.
This is Blade PHP code with query.
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Students:</strong>
<div style="margin-top: 5px" >
<?php $conn = new mysqli('localhost', 'root', '', 'rp') or die ('Cannot connect to db');
$result = $conn->query("select users.id, users.name from users, model_has_roles where model_has_roles.model_id=users.id and model_has_roles.role_id=14;
");
echo "<html>";
echo "<body>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<form><input type=checkbox name="student_id[]" value="'.$id.'">'.$name.'</form>'; }
//echo "</select>";
echo "</body>";
echo "</html>";?>
He is my function code in Controller
public function update(Request $request, Ticket $ticket){
request()->validate([
'gpname' => 'required',
'detail' => 'required',
'semester' => 'required',
'gender' => 'required',
// 'status',
// 'Assigned',
]);
$users= Auth::user();
$rr= $users->roles->pluck('name')->toArray();
// dd($users->id);
// $data= $request->all();
//$ticket = new Ticket;
if($rr[0]=='Admin'){
$data= $request->all();
//dd($data['Assigned']) ;
$ticket->gpname=$data['gpname'];
$ticket->detail=$data['detail'];
$ticket->semester=$data['semester'];
$ticket->gender=$data['gender'];
//dd("hhh");
$student_id = array("student_id");
if(isset($_POST['submit'])){
if(!empty($_POST['student_id'])){
$student_id = $_POST['student_id'];
foreach($student_id as $id){
// echo $id.'<br/>';
dd($data['student_id']);
}
}
}
dd($data['student_id']);
//dd( $data['student_id[]']);
//$ticket->studentnames=$users->empid;
$ticket->user_id=$users->id;
//$ticket->Assigned=$data['Assigned'];
$ticket->save();
and as you see if I make dd($data['student_id']); as a comment it's never going to the previous one inside foreach()
How I can get multiple values from the checkbox?
dd(); is killing the loop and returning only the first value you should echo your results instead of dd(); them or use.
if(!empty($_POST['student_id'])){
$student_id = $_POST['student_id'];
$array_test = []
foreach($student_id as $id){
if($id == $data['student_id']){
array_push($id, $array_test)
}
}
dd($array_test);
}
Since i don't know what are you trying to do so i will drop the second thought
if(!empty($_POST['student_id'])){
$student_id = $_POST['student_id'];
$array_test = []
foreach($student_id as $id){
array_push($id, $array_test)
}
dd($array_test);
}
Related
I have three tables: books, editions, and listings.
I have one form where a user can select a book, then a book edition and all of the fields (title, author, year, publisher, edition year, etc.) fill in automatically. If the user selects "My book isn't on this list", then he has to fill in the fields himself. The fields related to the listings table have to be filled by the user himself in any case:
this is how the form looks like
I'm trying to use the Laravel UpdateOrCreate method on submit, so only the new information is added to the database:
public function store(Request $request) {
Book::UpdateOrCreate([
'id' => $request->get('id'),
],
[
'book_title' => $request->get('book_title'),
'book_author' => $request->get('book_author'),
'book_description' => $request->get('book_description'),
'book_year' => $request->get('book_year'),
'book_language' => $request->get('book_language'),
]);
Edition::UpdateOrCreate([
'id' => $request->get('eid'),
],
[
'book_id' => $request->get('id'),
'image_url' => $request->get('image_url'),
'publisher' => $request->get('publisher'),
'edition_year' => $request->get('edition_year'),
'pages' => $request->get('pages'),
'cover_type' => $request->get('cover_type'),
]);
$listing = new Listing();
$listing->user_id = $request->get('user_id');
$listing->edition_id = $request->get('eid');
$listing->listing_description = $request->get('listing_description');
$listing->price = $request->get('price');
$listing->condition = $request->get('condition');
$listing->shipping_type = $request->get('shipping_type');
$listing->image_url = $request->get('listing_image');
$listing->save();
return redirect()->route('new-listing')->with('message', 'Listing added succesfuly!');
}
This is what automatically fills the input fields (just regular inputs with name attributes such as book_title, book_author and the rest that are in my UpdateOrCreate method above.
<div class="row">
<?php
header('Content-Type: text/html; charset=utf8');
$servername = "localhost";
$username = "thriftyourbook-user";
$password = "123";
$dbname="thriftyourbook";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
$qu = "SELECT book_title,book_author,book_description,book_year,book_language,id FROM books ORDER BY book_title";
$res = $conn->query($qu);
$q = "SELECT e.image_url,e.publisher,e.edition_year,e.pages,e.cover_type,e.id,b.book_title FROM editions as e JOIN books as b ON e.book_id = b.id ORDER BY b.book_title";
$re = $conn->query($q);
?>
<div class="form-group col-6">
<label for="book">{{ __('l.selectbook') }}</label>
<select id="book" class="form-control" name="book" onchange="bookInfo()">
<option value="no">{{ __('l.onthislist') }}</option>
<?php
while($r = mysqli_fetch_row($res))
{
echo "<option value=\"yes\" data-id=\"$r[5]\" data-ttl=\"$r[0]\" data-auth=\"$r[1]\" data-desc=\"$r[2]\" data-yr=\"$r[3]\" data-lang=\"$r[4]\" value=\"$r[5]\"> $r[0] </option>";
}
?>
</select>
</div>
<div class="form-group col-6" id="edition-field-div">
<label for="edition">{{ __('l.selectedition') }}</label>
<select id="edition" class="form-control" onchange="editionInfo()">
<option value="no">{{ __('l.editionnotlist') }}</option>
<?php
while($r = mysqli_fetch_row($re))
{
echo "<option value=\"yes\" data-img=\"$r[0]\" data-pblshr=\"$r[1]\" data-eyr=\"$r[2]\" data-pg=\"$r[3]\" data-cov=\"$r[4]\" data-eid=\"$r[5]\" data-titl=\"$r[6]\" value=\"$r[5]\">
$r[6] ($r[1], $r[2], $r[3] pages, ";
if ($r[4] == 'HC') {
echo "Hardcover) </option>";
} elseif ($r[4] == 'PB') {
echo "Paperback) </option>";
}
}
?>
</select>
</div>
</div>
No errors are returned, but every time I submit the form, every field related to the books or editions table becomes empty. Only the listing information is filled correctly.
Thanks in advance for any help! :)
I've small blog users can add new post and others can comment on this post ( Post is working perfectly, comments is working too )
all posts is showing and all comment is showing but each Separated , how can I display it related.
function getPostInfoo(){
if($this->num_members < 0){
$q = "SELECT * FROM ".TBL_POSTS;
$result = mysqli_query($this->connection, $q);
$fields = array();
while($fetch=mysqli_fetch_array($result)){
echo "
<h3>".$fetch['post']."</h3>
<p>".$fetch['username']."</p>";
}
$this->num_members = mysqli_fetch_array($result);
}
//return
return $fields;
}
function getComment(){
$q = "SELECT ".TBL_POSTS.".*, ".TBL_COMMENTS.".*
FROM ".TBL_POSTS."
INNER JOIN ".TBL_COMMENTS." ON ".TBL_COMMENTS.".postid=".TBL_POSTS.".postid";
$result = mysqli_query($this->connection, $q);
/* Error occurred, return given name by default */
if(!$result || (mysqli_num_rows($result) < 1)){
return NULL;
}
$fields = array();
while($fetch=mysqli_fetch_array($result)){
$fields[] = "<p><a href='#'>".$fetch['username'].": </a>".$fetch['comment']."<br>
<small class='text-muted'>".$fetch['cmntdate']."</small>
</p>
";
}
/* Return result array */
return $fields;
}
test.php
echo "<div>";
$myList2 = $database->getPostInfoo();
if (is_array($myList2) || is_object($myList2)){
foreach($myList2 as $arrayItem2){
echo $arrayItem2;
}
}else {
echo "No Posts yet.";
}
echo "</div>
<div>";
$myList = $database->getComment();
if (is_array($myList) || is_object($myList)){
foreach($myList as $arrayItem){
echo $arrayItem;
}
}else {
echo "No comments yet.";
}
<form method='post' action='functions.php' method='POST'>
<div class='form-group' >
<textarea class='form-control' name = 'comment' placeholder='Write Comment'></textarea>
<input type='hidden' name='postid' value='1'>
<input type='hidden' name='comment_sub' value='1'>
<input type='submit' value='Add Comment!'>
</div>
</form>
</div>";
what I need to do is to display each comments on its own post & show comment textarea on each post
Please see the image https://i.stack.imgur.com/A4D55.jpg
You need to be getting one post at a time and then fetch its comments.
So your test.php should look this test.php?id=post_id
Where post_id is the unique identifier of your post based on your db structure
Could be e.g is 1 or 2 or if you are using auto-increment id
Then you can add the following code to at the beginning of your test.php to get the post id
$post_id = isset($_GET['id']) ? $_GET['id'] : '';
The fetch the post and it's comment from your table using the value of $post_id
Hope it helps
Try this function:
function getPostsInfo(){
$q = "SELECT ".TBL_POSTS.".`id`,".TBL_POSTS.".`post`, ".TBL_POSTS.".`username`, ".TBL_COMMENTS.".`username` as comment_username, ".TBL_COMMENTS.".`comment`, ".TBL_COMMENTS.".`cmntdate`
FROM ".TBL_POSTS."
LEFT JOIN ".TBL_COMMENTS." ON ".TBL_COMMENTS.".postid=".TBL_POSTS.".postid";
$result = mysqli_query($this->connection, $q);
$posts = [];
while($fetch=mysqli_fetch_array($result)){
if(isset($posts[$fetch["id"]])){
$posts[$fetch["id"]]["comments"][] = [
"username" => $fetch["comment_username"],
"comment" => $fetch["comment"],
"cmntdate" => $fetch["cmntdate"]
];
}else{
$posts[$fetch["id"]] = [
"post" => $fetch["post"],
"username" => $fetch["username"],
"comments" => [[
"username" => $fetch["comment_username"],
"comment" => $fetch["comment"],
"cmntdate" => $fetch["cmntdate"]
]]
];
}
}
return $posts;
}
How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>
Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.
If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>
to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}
So I have these code below. The first one is a loop which echos all the requirements came from the database and write it in a checkbox form. So what I did is named it in an array form which is requirementItems[].
The next code is all about checking and inserting. If the checkbox is checked, the $state variable will have the value of 1 else, 0.
My problem is that, when I tried to leave a checkbox unchecked, it doesn't record into the database. But if it is checked, it successfully insert the data.
FIRST
<?php
$query = $db->prepare("SELECT * FROM tbl_requirements WHERE reqStatus = 1");
$query->execute();
while($result = $query->fetch(PDO::FETCH_ASSOC)){
$requirementID = $result['reqID'];
$requirementName = $result['reqName'];
echo "
<div class='row'>
<div class='col-md-5'>
<div class='checkbox'>
<label>
<input type='checkbox'value='$requirementID' title='$requirementID' name='requirementItems[]'>
$requirementName
</label>
</div>
</div>
</div>
";
}
?>
SECOND
<?php
if(isset($_POST['passSubmit'])){
$rsrvReqID = trim($_POST['reqID']);
$customerID = $_GET['cusID'];
$reservedProperty = $_GET['propertyID'];
$paymentID = $_GET['paymentID'];
$requirementItems = $_POST['requirementItems'];
foreach($requirementItems as $reqItem) {
$state = (isset($reqItem)) ? 1 : 0;
$query = $db->prepare("INSERT INTO tbl_rsrvrequirements (rsrvReqID, customerID, propertyID, paymentID, reqID, rsrvReqState)
VALUES (:rsrvReqID, :customerID, :reservedProperty, :paymentID, :reqID, :state)");
$query->execute(array(
":rsrvReqID" => $rsrvReqID,
":customerID" => $customerID,
":reservedProperty" => $reservedProperty,
":paymentID" => $paymentID,
":reqID" => $reqItem,
":state" => $state
));
$reqNEW = str_replace('REQ','',$rsrvReqID);
$requireID = str_pad(trim($reqNEW) +2,7,0,STR_PAD_LEFT);
$rsrvReqID = 'REQ'.$requireID;
}//foreach()
echo"<meta http-equiv='refresh' content='0; url=summary.php?reqID=$rsrvReqID' >";
}//if(isset())
?>
i want to update the fields below but my form is not working. it is not storing data what should i do. i used jquery accordion fo r the fields so it will click the item he wants to edit then update the fields then submit. but it is not working.
VIEW
foreach($people as $row){
echo "<h3>".$row->service."</h3>";
echo "<form action='".base_url()."some_controller/updateCI' method='post'> <div>Service ID: <input type=text name=id value='".$row->id."' size=27px/><br>Service Name: <input type=text name=name value='".$row->service."'><input type='button' class='classname' value='Save'/></form></div>";
}
?>
CONTROLLER
public function updateCI(){
$this->load->model('some_model');
$id = $this->input->post('id');
$servName = $this->input->post('name');
$success = $this->some_model->updateCI($id,$servName);
if($success == TRUE)
$this->editCI_page(TRUE);
else $this->editCI_page(FALSE);
}
MODEL
public function updateCI($id,$servName){
//$name = $this->db->escape_str($name);
$appID = $this->db->escape_str($id);
$ciName = $this->db->escape_str($servName);
$queryStr = "UPDATE appwarehouse.service SET id='$appID',service='$ciName' WHERE id = '$appID';";
$query = $this->db->query($queryStr);
return $query;
}
You can do something like this in your model:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
I would recommend you to use the active record which are available for codeigniter. For more information visit the below link:
http://ellislab.com/codeigniter/user-guide/database/active_record.html