I have a PHP Object Array with several fields and I need to extract all the equal fields and store them into individual arrays, because I need to pass them to a bash script, and I prefer to have separate arrays, because bash is no object oriented right?
Here is what I'm trying to do:
<?php
$data = json_decode($_POST['data']);
$text_array = "'" . implode ("\n", $data->text) . "'";
$time_text = "'" . implode ("\n", $data->time_text) . "'";
$gender = "'" . implode ("\n", $data->gender) . "'";
$pitch = "'" . implode ("\n", $data->pitch) . "'";
$response = shell_exec("./test_bash.sh $pitch $gender $timetext $text_array 2>&1");
echo "$response";
?>
The data is passed from javascript to PHP through ajax. The original Object Array has this structure:
text
time_text
gender
pitch
and I create the Object Array in Javascript like:
function dataClass(text, time_txt, gender, pitch, mood) {
this.text = text;
this.time_text = time_txt;
this.gender = gender;
this.pitch = pitch;
this.mood = mood;
}
for(var i = 0; i < length - 1; i++){
data.push(new dataToSynth(subtitles_trans[i].text, subtitles_trans[i].end - subtitles_trans[i].start, genere, pitch));
}
How can I copy the object array fields to a individual arrays, in PHP?
You don't need to use json_decode. In your case "$_POST['data']" is an array, not an object. Try this code:
$data = $_POST['data'];
$text_array = "'" . implode ("\n", $data['text']) . "'";
$time_text = "'" . implode ("\n", $data['time_text']) . "'";
$gender = "'" . implode ("\n", $data['gender']) . "'";
$pitch = "'" . implode ("\n", $data['pitch']) . "'";
You can cast object values into array just you cast an string to int.
<?php
class a{
public $a="a";
public $b="b";
public $c="c";
}
$a= new a();
$b= (array)$a;
var_dump($a);
/*object(a)#1 (3) {
["a"]=>
string(1) "a"
["b"]=>
string(1) "b"
["c"]=>
string(1) "c"
}*/
var_dump($b);
/*array(3) {
["a"]=>
string(1) "a"
["b"]=>
string(1) "b"
["c"]=>
string(1) "c"
}*/
So it should be like this:
<?php
$data =(array) json_decode($_POST['data']);
$text_array = "'" . implode ("\n", $data['text']) . "'";
$time_text = "'" . implode ("\n", $data['time_text']) . "'";
$gender = "'" . implode ("\n", $data['gender']) . "'";
$pitch = "'" . implode ("\n", $data['pitch']) . "'";
$response = shell_exec("./test_bash.sh $pitch $gender $timetext $text_array 2>&1");
echo "$response";
?>
Related
I'm looking to find out how I can tell if a filename contains two or more dots.
eg. 45FGG.TESTDOC.MAY12.png, carimage.30.jpg.
So, how to store this image with its extension?
You can easily count the dots with regex:
PHP
preg_match_all("/\./", "45FGG.TESTDOC.MAY12.png"); // 3
JS
"45FGG.TESTDOC.MAY12.png".match(/\./g).length; // 3
Here are two test cases:
$file1 = "hello.jpg";
$file2 = "hello.file.jpg";
echo "\$file1: " . $file1 . "\n";
echo "\$file2: " . $file2 . "\n\n";
echo "Position of \$file1's first '.' : " . strpos($file1, '.') . "\n";
echo "Position of \$file1's last '.' : " . strripos($file1, '.') . "\n";
echo "Position of \$file2's first '.' : " . strpos($file2, '.') . "\n";
echo "Position of \$file2's last '.' : " . strripos($file2, '.') . "\n\n";
if (strpos($file1, '.') != strripos($file1, '.'))
{
echo "\$file1 has >= 2 dots\n";
}
else
{
echo "\$file1 has 1 dot \n";
}
if (strpos($file2, '.') != strripos($file2, '.'))
{
echo "\$file2 has >= 2 dots\n";
}
else
{
echo "\$file2 has 1 dot \n";
}
Output:
$file1: hello.jpg
$file2: hello.file.jpg
Position of $file1's first '.' : 5
Position of $file1's last '.' : 5
Position of $file2's first '.' : 5
Position of $file2's last '.' : 10
$file1 has 1 dot
$file2 has >= 2 dots
I need to embed PHP into Javascript so that when the user selects Countries it would display the result from the query alphabatically and if he selects Numbers then list based on numbers in descending.
Having researched, I have applied this (echo concept into my code) but doesn't seem to work.
I have the following query written in PHP that output staffs' country of birth( no of staff born in number of countries) in ascending order:
$querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) ASC ";
Then, I have a dropdown in HTML:
<form>
<label for="sortorder">Sort by:</label>
<select id="sortByDropdown" onchange="sortBy(this);">
<option value="alphabatically">Countries</option>
<option value="numbers">Number</option>
</select>
</form>
Furthermore, I have a Javascript function sortBy()
function sortBy(){
var sortByDrpdownDiv = document.getElementById('sortByDropdown');
if (sortByDrpdownDiv[sortByDrpdownDiv.selectedIndex].value == 'numbers'){
alert("yo in if statement");
<?php $querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC ";
$result = mysql_query($querytest);
while ($row = mysql_fetch_assoc($result)) {
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}?>
document.getElementById('staffbirthplaces').innerHTML = <?php echo $row?>;
}
}
First I am going only for Numbersbecause the same logic will apply to the Countries. Any help will be appreciated
So, i finally did it! Used switch instead of IF statement. Below is the code:
function sortByAlphabetsOrNumbers(obj){
var selectedValue = obj.options[obj.selectedIndex].value
switch(selectedValue)
{
case "numberOfStaff":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$staffNumbersDesc = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC";
$result = mysql_query($staffNumbersDesc);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
case "countries":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$alphabaticalOrder = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x";
$result = mysql_query($alphabaticalOrder);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
}
};
Hope it helps someone
Here are my files:
Backend Search PHP File:
<?php
require "../sinfo.php";
function chk_phone($orig) {
return preg_replace("/[^0-9]/","",$orig);
}
$s = $_POST["s"];
$sql = "SELECT * FROM requests WHERE id LIKE '%" . $s . "%' OR " .
"lower(firstname) LIKE '%" . strtolower($s) . "%' OR " .
"lower(lastname) LIKE '%" . strtolower($s) . "%' OR " .
"dayphone LIKE '%" . strtolower($s) . "%' ORDER BY id ASC";
$result = $conn->query($sql);
$valid = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row["status"] == "Complete" && date_compare($row["timestamp"]) < 37) {
$valid[] = $row;
}
}
}
if (count($valid) > 0) {
echo "<ul>\n";
foreach ($valid as $row) {
echo "<li onclick=\"javascript: autofill('" . $row["id"] . "', '" .
$row["firstname"] . "', '" .
$row["lastname"] . "', '" .
chk_phone($row["dayphone"]) . "', '" .
chk_phone($row["evephone"]) . "', '" .
$row["email"] . "', '" .
$row["make"] . "', '" .
$row["os"] . "', '" .
htmlspecialchars($row["issue"]) . "', '" .
$row["password1"] . "', '" .
$row["password2"] .
"');\">" . $row["id"] . " - " . $row["firstname"]. " " . $row["lastname"] . "</li>\n";
}
echo "</ul>\n";
} else {
echo "-- No Results Found --";
}?>
Here is the javascript file:
function upsearch(content) {
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}
catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Something went wrong.!\nError: \n" + e);
return false;
}
}
}
xmlhttp.onreadystatechange = function() {
//if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
//}
};
var params = "s=" + content;
xmlhttp.open("POST", "ajax/requestsearch.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function autofill(rid, fname, lname, dphone, ephone, email, make, os, issue, password1, password2) {
document.getElementById("searchrid").value = rid;
document.getElementById("searchrid").disabled = true;
document.getElementById("custinfo").style.display = "block";
document.getElementById("firstname").value = fname;
document.getElementById("firstname").disabled = true;
document.getElementById("lastname").value = lname;
document.getElementById("lastname").disabled = true;
document.getElementById("dayphone").value = dphone;
document.getElementById("evephone").value = ephone;
document.getElementById("email").value = email;
document.getElementById("equipinfo").style.display = "block";
document.getElementById("make").value = make;
document.getElementById("make").disabled = true;
document.getElementById("password1").value = password1;
document.getElementById("password2").value = password2;
document.getElementById("originalissue").style.display = "block";
document.getElementById("originalissue").innerHTML = issue;
document.getElementById("os").value = os;
}
On the main PHP page that calls the backend page, I get all the results as expected. It displays as I want and everything. My problem is that all the lines it returns, some of them don't perform the javascript "autofill" function, while others do. It's always the same ones, so it doesn't matter if the search is done in different ways. The only thing that I could think of that could cause problems was the "issue" field from my database can have html elements, but I fix that with the htmlspecialchars() function. Before I switched it to a POST method, I was using the GET method and I would pull that same page up with the same search results and look at the code, and it would all be correct, even those ones that would not perform the function. I switched it to the POST method to see if it would make a difference, but its the exact same problem. This same problem occurs in Chrome and IE. What am I doing wrong? Or what should I do differently.
I would suggest You to use jQuery.
Just use simple ajax request like:
$.ajax({
type: 'POST',
url: 'ajax/requestsearch.php',
data: 'q='+query,
success: function(data){
var r = $.parseJSON(data);
autofill(r[0].lastname,r[0].firstname, r[0].phone, etc);
}
});
and requestsearch.php
$q = $_POST['q'];
$sql="SELECT * FROM DataBase WHERE firstname LIKE '%$q%' ORDER BY firstname asc";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
Edit: I've tried to follow the instructions and apparently everytime a query is executed a new array is added, but, when i generate the JSON file, the second array contains the values of the first array and those of the second. What's wrong with this?
Here's my problem: i have to solve two problems:
1) I have to create a JSON file with PHP consisting of a succession of several arrays, like in the following example:
{
"data": {
"cliente": [
{
"id": "Sentra",
"nome": 4,
"cognome": "Sentra",
"indirizzo": 4,
"email": "Sentra",
"tipo_contatto": 4,
"telefono_1": "Sentra",
"telefono_2": 4,
"telefono_3": "Sentra"
}
],
"accettazione": [
{
"id": "Sentra",
"nome": 4,
"cognome": "Sentra",
"indirizzo": 4,
"email": "Sentra",
"tipo_contatto": 4,
"telefono_1": "Sentra",
"telefono_2": 4,
"telefono_3": "Sentra"
},
{
"id": "Taurus",
"data": 4,
"id_operatore": "Taurus",
"dispositivo": 4,
"note": "Taurus",
"password": 4,
"tipo_avviso": "Taurus",
"id_cliente": 4,
"difetto_dichiarato": "Taurus",
"codice": 4
}
]
}
}
Here i have two arrays, but i need to have loads of them, anyway, in my PHP page, here's what i have:
<?php
session_start();
include_once('UniversalConnect.php');
class Login
{
private $hookUp;
private $sql;
private $sql2;
private $sql3;
private $sql4;
public function __construct()
{
$this->hookUp = UniversalConnect::doConnect();
$this->sql = "SELECT * FROM cliente";
$this->sql2 = "SELECT * FROM accettazione";
$this->sql3 = "SELECT * FROM riparazione";
$this->sql4 = "SELECT * FROM operatore";
// Tabella cliente
$response = array();
$data = array();
if ($result = $this->hookUp->query($this->sql)) {
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['nome'] . "</td>";
echo "<td>" . $row['cognome'] . "</td>";
echo "<td>" . $row['indirizzo'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['tipo_contatto'] . "</td>";
echo "<td>" . $row['telefono_1'] . "</td>";
echo "<td>" . $row['telefono_2'] . "</td>";
echo "<td>" . $row['telefono_3'] . "</td>";
echo "</tr>";
$data[] = array("id" => $row['id'], "nome" => $row['nome'], "cognome" => $row['cognome'], "indirizzo" => $row['indirizzo'], "email" => $row['email'], "tipo_contatto" => $row['tipo_contatto'],
"telefono_1" => $row['telefono_1'], "telefono_2" => $row['telefono_2'], "telefono_3" => $row['telefono_3']);
$response['cliente'] = $data;
$fp = fopen("cliente.json", "w");
fwrite($fp,json_encode($response));
fclose($fp);
}
}
// Tabella accettazione
if ($rs = $this->hookUp->query($this->sql2)) {
while ($rw = mysqli_fetch_array($rs, MYSQLI_BOTH)) {
echo "<tr>";
echo "<td>" . $rw['id'] . "</td>";
echo "<td>" . $rw['data'] . "</td>";
echo "<td>" . $rw['id_operatore'] . "</td>";
echo "<td>" . $rw['dispositivo'] . "</td>";
echo "<td>" . $rw['note'] . "</td>";
echo "<td>" . $rw['password'] . "</td>";
echo "<td>" . $rw['tipo_avviso'] . "</td>";
echo "<td>" . $rw['id_cliente'] . "</td>";
echo "<td>" . $rw['difetto_dichiarato'] . "</td>";
echo "<td>" . $rw['codice'] . "</td>";
echo "</tr>";
$data[] = array("id" => $rw['id'], "data" => $rw['data'], "id_operatore" => $rw['id_operatore'], "dispositivo" => $rw['dispositivo'], "note" => $rw['note'], "password" => $rw['password'],
"tipo_avviso" => $rw['tipo_avviso'], "id_cliente" => $rw['id_cliente'], "difetto_dichiarato" => $rw['difetto_dichiarato'], "codice" => $rw['codice']);
$response['accettazione'] = $data;
$file = file_get_contents("cliente.json");
$data = json_decode($file);
unset($file);
file_put_contents("cliente.json", json_encode($data));
unset($data);
$fp = fopen("cliente.json", "w");
fwrite($fp,json_encode($response));
fclose($fp);
}
}
}
}
$worker = new Login();
?>
The file executes four queries. In the first i create the json file, and the first query creates the first array, then with the second i create the second, and the second, "accettazione", has to become the second array separated by a comma on the first one, and so on...
Unfortunately, when the second query is executed, the second array becomes the first array, it doesn't become the second after the first one. I know how to push new objects to an existing array, but that's not the situation.
2) The second question is about how this data should be generated in my page:
In the following code, when i click on a "a" tag, the "linked" piece of code (i don't attach it here, but it's an html div), the code is shown (it's an empty table), which has to host the JSON data. As you can see from the example, tmp_div is a sort of array which indicates the content (div 0, div 1, div 2, div3).
The idea is that, when I click on tmp_div 0, json.data.cliente have to be shown, and the same for the others, but i want to do it dinamically, not everytime specifying different cases. How do i have to edit the code to reach the goal?
<!--Funzione di selezione della voce del menu e dell'apparizione dei relativi dati-->
<script type="text/javascript">
$('.sidebar-menu a').click(function (e) {
hideContentDivs();
var tmp_div = $(this).parent().index();
$(".main-sections div").eq(tmp_div).show();
$.getJSON("lista.json", function(json){
if (tmp_div == 0) {
var data = json.data.cliente;
for (var i = 0; i < data.length; i++) {
var object = data[i];
for (property in object) {
var value = object[property];
console.log(property + "=" + value);
}
}
} else if (tmp_div == 1) {
var data = json.data.accettazione;
for (var i = 0; i < data.length; i++) {
var object = data[i];
for (property in object) {
var value = object[property];
console.log(property + "=" + value);
}
}
} else if (tmp_div == 2) {
var data = json.data.riparazione;
for (var i = 0; i < data.length; i++) {
var object = data[i];
for (property in object) {
var value = object[property];
console.log(property + "=" + value);
}
}
} else if (tmp_div == 3) {
var data = json.data.operatore;
for (var i = 0; i < data.length; i++) {
var object = data[i];
for (property in object) {
var value = object[property];
console.log(property + "=" + value);
}
}
}
});
});
function hideContentDivs() {
$(".main-sections div").each(function () {
$(this).hide();
});
}
hideContentDivs();
</script>
To answer your first question:
Unfortunately, when the second query is executed, the second array
becomes the first array, it doesn't become the second after the first
one. I know how to push new objects to an existing array, but that's
not the situation.
Right now you're calling $data = array() in your loop. You're overwriting the existing array each iteration of the loop. Because of that, $data[] = ... will always push to element 0, since it's pushing onto an empty array.
Furthermore, you're doing this: $response['cliente'] = $data; which means you will always rewrite $response with whatever $data is. This is not pushing new objects onto an existing array; you are always overwriting your arrays.
To answer your second question:
This is more of a design question in the end. You have a lot of possible answers. A very quick thing you can do for now would probably be make a function, but that's just a small step forward. You may have better advice in Code Review instead.
Im trying to extract links from an external site using php bot . The link is inside
<td class=" title-col"> News 1 </td>
Notice there is a space before " title-col".
Here is the script Im using which fails to extract the links
function crawl_page($url, $depth = 5) {
static $seen = array();
if (isset($seen[$url]) || $depth === 0) {
return;
}
$seen[$url] = true;
$dom = new DOMDocument('1.0');
//als tried true , but no change in results
$dom->preserveWhiteSpace = false;
#$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$td = $xpath->query('//td[contains(concat(" ", normalize-space(#class), " "), "title-col")]');
// also tried this, but not working
//$td = $xpath->query('//td[contains(#class,"title-col")]');
//I only get values when I use this
//$td = $dom->getElementsByTagName('td');
foreach( $td as $t ) {
$anchors = $t->getElementsByTagName('a');
foreach ($anchors as $element) {
$href = $element->getAttribute('href');
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($url, array('path' => $path));
}
else {
$parts = parse_url($url);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '#';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
crawl_page($href, $depth - 1);
}
}
echo "URL:" . $url . "<br/>";
}
I only get values when I use this
$td = $dom->getElementsByTagName('td');
But I need to query by class .
THanks
I figured out it was due to javascript generated attribute.