This question already has an answer here:
PHP into database with dynamic form with javascript (codeigniter)
(1 answer)
Closed 7 years ago.
I build an app but I found new problem, I want to insert multiple data using javascript to add more form dynamically (then insert into table). Okay in my FIGURE, number 1,2,3 that's clear. But when I insert into the table , it can't succesfully. (number 4 is my function to insert data, but all of may form cannot insert (number 5) , only 1 data can insert ). what's wrong ? thanks
FIGURE
use for loop like this, your $_POST must be under loop.
for ($i = 0; $i < count($_REQUEST['heading']); $i++) {
$heading = $_POST["heading"][$i];
$address = $_POST["address"][$i];
$array_addmore[$i] =
array(
"heading" => urlencode($heading),
"address" => urlencode($address)
);
}
Related
This question already has answers here:
JSON encode MySQL results
(16 answers)
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 months ago.
I need to how I can use data that I fetched from the database and put into a JSON Object inside a php-file in another (Javascript)-File, where the data is supposed to end up inside an array.
function loadApplicationList()
{
$email = $_GET['email'];
$listcontent = queryDB("
SELECT Application.FavRank, Proposal.Title, Proposal.pdfName, RegisteredUser.Name
FROM Application
LEFT JOIN user_application
ON Application.ID = user_application.ID AND user_application.eMail = '$email'
LEFT JOIN Proposal
ON Proposal.ID = Application.Proposal_ID
LEFT JOIN RegisteredUser
ON RegisteredUser.eMail = Proposal.AuthorEmail;");
$encodeContent = json_encode($listcontent);
}
?>
Above is the php code, below the JS code
let data = [
// this array is supposed to contain the data from the JSON Object
];
I should also mention that I am new to these languages, so I might've already 'found' the right answer during my hour long research online but wasn't capable to identify it. Thanks for your help in advance.
This question already has answers here:
PHP Array to JSON Array using json_encode(); [duplicate]
(4 answers)
json_encode PHP array as JSON array not JSON object
(4 answers)
PHP json_encode creates number index as string instead of an object
(1 answer)
Prevent json_encode() from automatically generating integer keys
(1 answer)
json with no index after unset encode array in php
(6 answers)
Closed 3 years ago.
any help would be really appreciated for an educational website I'm building that stores question results. I've searched a lot on this site but not found this issue specifically.
I'm really struggling to pass SQL data using PHP to Javascript so that it ends up as a multidimensional array (with no keys) rather than an object.
I'm currently getting an object like this in JS
{"0":["y3","y2","y1","n5","y4","y6"],"1":["n5","n4","n3","y","n","y"], ...}
What I really need is an array like
[["y3","y2","y1","n5","y4","y6"],["n5","n4","n3","y","n","y"]...]
so that I can perform other functions on it in JS (e.g. length, find index number etc).
Extract from my PHP and JS is below. I'm using echo json_encode and I've tried lots of different variations of mysqli_fetch but can't work it out. Strangely, a similar query on a different SQL table works as I'd like it to (the only difference is that it is returning lists of integers not strings).
// ...
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) > 0) {
//Fetch result row
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
array_push($thisFact, $row["mark"]); //"mark" is the column name in the table
}
$progress[$x] = $thisFact; // set progress for this Fact (an array of up to 6 items)
} // end if result > 0
}
else {
echo "Oops! can't execute. " ;
}
} //end loop
?>
var FactProgress = <?php echo json_encode($progress); ?>;
alert(FactProgress.length);
for (var i = 0; i < FactProgress.length; i++) {
FactProgress.length shows as undefined. It then falls over on the next line when I try to use the length.
Many thanks.
This question already has answers here:
INSERT array - PDO
(2 answers)
Binding values from arrays?
(3 answers)
Closed 5 years ago.
I have tried both the links but I don't get the expected variables content in $fields and $newdata
** This question has developed in a new one here **
PHP how to extract keys names and values from associative array for mysql query (as explained I'm newbie and it took some work to get the question asked in the right way)
so I kindly print here some var_dump and cast to kindly ask your support.
For simplicity in my learning experiment, I'm working with a dummy table of just 5 fields, as you see they are: selected, user_id, user_name, user_company and user_email.
Finally I have inserted just 2 rows of values.
Using this code
$Arr = (array)$data;
print_r ( $Arr );
I can see this output
Array (
[0] => Array ( [selected] => [user_id] => 3 [user_name] => nome3 [user_company] => azien3 [user_email] => email3 )
[1] => Array ( [selected] => 1 [user_id] => 6 [user_name] => nome6 [user_company] => azien6 [user_email] => email6 )
)
next I try to apply the code of your links
24 $fields = implode(",", array_keys($Arr));
25 $newdata = "'" . implode("','", $Arr) . "'";
26
27 var_dump($fields);
28 echo "<br><br>";
29 var_dump($newdata);
But something is wrong in my interpreteation or in my code , because the output is
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
string(3) "0,1"
string(15) "'Array','Array'"
can you kindly point out what's wrong?
e.g. is my array properly formed?
ORIGINAL QUESTION
I'm newbie and after further readings I got the point and hopefully now my question could result more simple. Thank you for any hint.
I have a bidimensional array since its records are coming from an html table.
The collection made on the html side generates an associative array so each row is like in the following example where, also, you can see, the keys are many
[item] => Array (
[0] => Array (
[unit] => "car"
[qty] => 3
[description] => "Description 1"
....
[key47] => "thin"
)
[1] => Array (
[unit] => "bike"
[qty] => 74
[description] => "Description 2"
....
[key47] => "large"
)
)
The mysql table name where I want to insert the items is named items_table
"unit" "qty" and "description" and all the remaining keys (total 47) are exactly the same names of the items_table columns
When on the php side I'd like to have a sort of automatic query generation maybe with PDO that would pick the columns names from the inner array keys names and will insert the corresponding key value in the correct column.
The goal is to avoid creating such a awkward and extremely long query.
Preferred method would be with PDO, avoid binding 47 keys.
This sort of automatism is also useful because in the future columns in the mysql table may being added and or removed and or renamed, so I'd like to forget about the query thinking only about properly editing the html table (on that side the array is already automatically generated with some javascript)
Do you think is possible to do this?
If yes how to?
Does this still need some foreach loop?
Thank you for helping
E.g.:
core_table
id* unit quantity description
1 car 3 Description 1
2 bike 74 Description 2
adjunct_table
core_id* meta_key* meta_value
1 47 Description of key n.47 first row
2 47 Description of key n.47 second row
* = (component of) PRIMARY KEY
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My question: I have a php search form in which I need the user to be able to redefine the search for only a part of the string.
Example (so far the user enter):
// Search Option
name: 20081111-1 //which means that the date of the item is 2008-11-11
Now, I would like the user to make a search which it will only include all the items in 2008 (desired user search):
// Search Option
name: 2008*
How can I make this option in my search? Then I can search in my database for this part of the string only.
Thanks!
Javascript:
var str = '200811111-1';
var hasSubString = str.indexOf('2008') > -1;
var startsWithString = str.indexOf('2008') == 0;
MySql:
Has Substring 2008:
select * from table where col like '%2008%'
Starts with 2008:
select * from table where col like '2008%'
Option 1:
You would take the PHP variable and replace the asterisk (*) with a percentage sign (%):
<?php
$name = $_POST['name']; // remember to sanitize it
$name = str_replace('*', '%', $name);
?>
You would then create a MySQL query using your variable:
$query = "SELECT * FROM table WHERE column LIKE '$name'";
Option 2:
Use a MySQL date query:
$query = "SELECT * FROM table WHERE YEAR(column) = '2008'";
Note that column should be a date or a datetime type.
You should add contextual help for users or even dropdowns with possible options, so they don't search for '20081', for example.
In this specific case you can use in your query
date like '%2008-%'
instead of
date = '2008-11-11'
that means search for rows where date field contains the following pattern "2008-".
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
With this in sql you search using a pattern in your case 2008, you can use regular expression for do dynamically searching only numbers that start by 2.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What I am trying to do is, get data from my MySQL database using a Javascript/JQuery GET request and place this information within an HTML table to display which shifts do not contain a User ID.
I am struggling to understand how to display the JSON get data on the page and how to place this within a table on the HTML page.
I am using PHP on my localhost server to retrieve the data and I am able to retrieve the information in a JSON string.
The function that does this is here:
function marketplaceShifts(){
include ('config.php');
$sql = "SELECT *
FROM shift
WHERE user_id IS NULL";
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$return = array();
foreach ($result as $row){
$return[]=array('id'=>$row['shift_id'],
'User id'=>$row['user_id'],
'Date of shift'=>$row['date_shift'],
'Start of Shift'=>$row['start_time'],
'End of Shift'=>$row['finish_time']);
}
$conn = null;
header('Content-type: application/json');
echo json_encode($return);
}
This is the function that retrieves the data that I am looking for and works when using Postman to show me the JSON strings with the information I need.
Using jQuery's $.getJSON(), you can grab JSON data from a URL, and do what you want with it, like rendering it on the page (you can also do it without the library). For this method, make sure you include jQuery in your page.
The request can be made that way:
$(document).ready(function(){
$.getJSON('path/to/your/json.php', displayData);
});
Then, just create a displayData() function to do the work:
function displayData(data){
var table = $('<table></table>'), // Create a table element
row = $('<tr></tr>'), // Create a row
keys = Object.keys(data[0]); // Grab the headings
for(var i=0, l=keys.length; i<l; i++){ // For each of them
var cell = $('<th></th>').text(keys[i]); // Create cell, insert text
row.append(cell); // Append cell to row
} // End for
table.append(row); // Append row to table
for(var i=0, l=data.length; i<l; i++){ // For each data element
row = $('<tr></tr>'); // Create row
for(var j=0, k=keys.length; j<k; j++){ // For each key
var cell = $('<td></td>').text(data[i][keys[j]]);// Create cell, insert value
row.append(cell); // Append cell to row
} // End for
table.append(row); // Append row to table
} // End for
$('body').append(table); // Append table to body
}
JS Fiddle Demo