sql 'shows' array on some columns - mysql

I have some basic code which collects chkbox & radio buttons yes/no answers etc. from a form and stores in mysql but some of the mysql submissions work (ie puts yes or no in the sql column) but some just show in sql column as 'array' - this is a sample of the code. $repeat shows as 'array' where as $inter shows as yes or no. The columns in mysql are identical in structure the form HTML is the same syntax for both, the $_POST arrays are comma separated as I also email the values and the email displays the answers correctly - this is just odd
<?php
$repeat = "";
foreach ($_POST['repeat'] as $key => $value) {
$repeat.= ",$value ";
}
$repeat = substr($repeat,1);
$inter = "";
foreach ($_POST['intermitant'] as $key => $value) {
$inter.= ",$value ";
}
$inter = substr($inter,1);
//other posts all looped though etc
//then the sql - log on etc
$sql="INSERT INTO faults (repeat_visit,intermitant) VALUES ('$repeat','$inter')";
This is the HTML - Nothing odd about it that I can see, I get what you describe above - but why does one work and the other not with the same code, the same method is applied to checkboxes and some wiork fine other put 'array' in sql
<label>Repeat Visit:</label>
<input type="radio" name="repeat[]" value="Yes" />Yes
<input type="radio" name="repeat[]" value="No" />No
<label>Intermitant Fault:</label>
<input type="radio" name="intermitant[]" value="Yes" />Yes
<input type="radio" name="intermitant[]" value="No" />No

As popnoodles stated, seeing the form's HTML would help, but this looks as if each element in $_POST['repeat'] & $_POST['intermitant'] is actually an array, and so the $value of the foreach() is returning "Array"
Check that the checkbox array is only 1 dimensional, and if it is not, does it have to be multi-dimensional?
If so, perhaps a recursive function or nested loop to implode the values is required
$repeat = "";
foreach ($_POST['repeat'] as $k => $v)
{
foreach ($v as $kInner => $vInner)
{
$repeat .= ",$vInner ";
}
}

Related

data is not inserting into database in codeigniter

actually i am having student records in $students array and there is another array within $students, whose name is skill[], which is a checkbox form field name, so pls tell me how to use json_encode and where.
input form
<td>ENTER SKILLS</td>
<td>
<input type="checkbox" name="skills[]" value="php">php<br>
<input type="checkbox" name="skills[]" value="dotnet">dotnet<br>
<input type="checkbox" name="skills[]" value="java">java<br>
<input type="checkbox" name="skills[]" value="ruby_on_rails">ruby_on_rails<br>
</td>
controller
<?php
public function insert(){
if ($this->input->post('add')==true)
{
$student = array( 'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'skills' => $this->input->post(json_encode(skills)),
'notes' => $this->input->post('notes'),
'gender' => $this->input->post('gender') );
$result = $this->Student_info_model->insertStudent($student);
if($result==true){
echo "inserted";
}
else {
echo "Not Inserted";
}
}
}
?>
model
function insertStudent($student){
$this->db->insert('student_info_table', $student); // insert data into "student_info_table" table`
if ($this->db->affected_rows() > 0) {
return true;
}
else {
return false;
}
}
error
Error Number: 1048
Column 'skills' cannot be null
INSERT INTO `student_info_table` (`name`, `email`, `skills`, `notes`, `gender`) VALUES ('gailyn', 'quentin#gmail.com', NULL, 'dsas', 'male')
Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php
Line Number: 691
As far as i understand you want to get the array of skills from the http request and then to encode it and save it to your database. For that please use json_encode($this->input->post('skills') instead of $this->input->post(json_encode(skills)), so you first get the data, and then apply the json encoding over it.
Try with this : json_encode($this->input->post('skills')) You need to get the value of skills using input post and then need to convert it using json_encode

HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.
I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.
I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?
Here is my current code:
<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button>
<hr>
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);
if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];
?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
}
}
?>
</div>
</form>
if(isset($_POST['remove_dates'])){
$date_id = $_POST['date_id'];
}
I believe if you add this: [], to the name attribute, like this: <input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">. Then it will be handled as an array, which you can loop through with a foreach loop. and insert it into a database (or whatever you like).
Declare the name as an array, like as follows:
<input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">.
On submitting it will be handled as an array,
Then, you can loop the values of an array and for each element of an array use the id to remove the dates.

Accessing data from Wikidata JSON file

I'm trying to access the following properties from the Wikidata API: id, url, aliases, description and label but so far have been unsuccessful. I'm sure I'm making basic mistakes and so far only have the following code. Any suggestions as to the best way to access this data is much appreciated.
<html>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=Google&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
}
?>
</body>
</html>
Edit - I have managed to get a string ($jsonArr) containing particular data that I would like. However I would like to get the first instance of the particular elements from the string specifically id, url, alias, description and label i.e. specifically: variable1 - Q95, variable2 - //www.wikidata.org/wiki/Q95, variable3 - Google.Inc, varialbe4 - American multinational Internet and technology corporation, variable5 - Google/ Please see code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
You need to show the JSON you want to parse...
Basicly you can get values out of JSON in PHP like this...
If $doc is the JSON you want to parse
$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];
Edit after understanding what you are doing there :-)
Hi, Im sorry I was completely confused of what you were doing there... So I have testet your code on my server and just get what you want...
Following the code you wanted... I took clear var names, so they are a little bit longer, but easier to understand...
$searchString = urlencode($_POST['q']); //Encode your Searchstring for url
$resultJSONString = file_get_contents("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=".$searchString."&format=json&language=en"); //Get your Data from wiki
$resultArrayWithHeader = json_decode($resultJSONString, true); //Make an associative Array from respondet JSON
$resultArrayClean = $resultArrayWithHeader["search"]; //Get the search Array and ignore the header part
for ($i = 0; $i < count($resultArrayClean); $i++) { //Loop through the search results
echo("<b>Entry: ".$i."</b>");
echo("<br>");
echo($resultArrayClean[$i]["id"]); //Search results value of key 'id' at position n
echo("<br>");
echo($resultArrayClean[$i]["url"]); //Search results value of key 'url' at position n
echo("<br>");
echo($resultArrayClean[$i]["aliases"]); //Search results value of key 'aliases' at position n
echo("<br>");
echo("<br>");
echo("<br>");
}

Inserting multiple row in mysql with codeigniter

I am trying to upload multiple images with description in codeigniter. Everything is fine, image is uploaded, image filename is sent to database however "description" is not going to database, where did i mistake ?
form code is like this
File 1: <input type="file" name="image1" /><br />
Descr: <input type="text" name="description[]" size="50" value="" /><br/><br/>
File 2: <input type="file" name="image2" /><br />
Descr: <input type="text" name="description[]" size="50" value="" /><br/><br/>
File 3:<input type="file" name="image3" /><br />
Descr: <input type="text" name="description[]" size="50" value="" /><br/><br/>
and model is this
for($i = 1; $i < 6; $i++) {
/* Handle the file upload */
$upload = $this->upload->do_upload('image'.$i);
/* File failed to upload - continue */
if($upload === FALSE) continue;
/* Get the data about the file */
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
/* If the file is an image - create a thumbnail */
if($data['is_image'] == 1) {
$configThumb['source_image'] = $data['full_path'];
$this->image_lib->initialize($configThumb);
$this->image_lib->resize();
}
$image['raw'] = $data['raw_name'];
$image['ext'] = $data['file_ext'];
$image['newsid'] = $_POST['newsid'];
$image['description'] = $_POST['description'][$i];
$this->db->insert('multipics', $image);
}
Please note that the above code makes multiple rows insertion, I just need the description field to go in database
As a work around, I would get the POST variable first outside of the loop:
// (1) Get the POST description variable outside of the look
// As a precaution, dump or echo $description to make sure it looks right...
$description_ = $this->input->post('description');
for ($i = 1; $i < 6; $i++)
{
...
// Put some checks to make sure $i is an index...
$image['description'] = $description[$i];
...
}
Try this and let us know how you get on!
Change Change name="description[]" to name="description
You may also want to look at CI's insert_batch() method. This will let you insert all of the records with one query.

Submit form to calculate quadratic equation

Am just learning html. I need to write code that solves the quadratic equation formula. I tried php code embeding in html but am getting blank output. How do I get user values a, b, c and display conditional answers?
Here's a simple example of what you need to do. First make a HTML form:
<form method="post" action="index.php">
<input type="text" name="a" value="Enter 'a'" />
<input type="text" name="b" value="Enter 'b'" />
<input type="text" name="c" value="Enter 'c'" />
<input type="submit" name='calc' value="Calculate" />
</form>
There is your form. Now the calculations:
<?php
// Check if the form is submitted
if (isset($_POST['calc'])) {
//assign variables
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
//after assigning variables you can calculate your equation
$d = $b * $b - (4 * $a * $c);
$x1 = (-$b + sqrt($d)) / (2 * $a);
$x2 = (-$b - sqrt($d)) / (2 * $a);
echo "x<sub>1</sub> = {$x1} and x<sub>2</sub> = {$x2}";
} else {
// here you can put your HTML form
}
?>
You need to do more checks on it, but as I said before this is a simple example.
Edit: learn from the source , the official php site: http://php.net/manual/en/tutorial.forms.php
1.Create a form with the fields you want. <form method='post' ....>...</form>
2.The user submit the form and then write a PHP code which get the posted data ($_POST)
and manipulate it according to the quadratic equation formula.
3.Echo the result.
I have smaller example.
This file sends data from form to itself. When it sends something - result of condition
$_SERVER['REQUEST_METHOD']=='POST'
is true. If its true - server process code in "if" block. It assigns data sent from form to 2 variables, then adds them and store in "$sum" variable. Result is displayed.
<html>
<body>
<form method="POST">
<p>
A: <br />
<input name="number_a" type="text"></input>
</p>
<p>B: <br />
<input name="number_b" type="text"></input>
</p>
<p>
<input type="submit"/>
</p>
</form>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') // process "if block", if form was sumbmitted
{
$a = $_POST['number_a'] ; // get first number form data sent by form to that file itself
$b = $_POST['number_b'] ; // get second number form data sent by form to that file itself
$sum = $a + $b; // calculate something
echo "A+B=" . $sum; // print this to html source, use "." (dot) for append text to another text/variable
}
?>
</body>
</html>
You need PHP server to test/use this! PHP file must be processed by web server, which creates page. Opening php file from disk will not work. If you need more explanations - ask for it in comments.