What's wrong with this database call? - php

-Issue Still Unresolved-
I'm trying to call a database, put all the rows of a table in an array, pass that table to my JS as json data, and then use that data as parameters for a function.
When I run the script nothing happens. I don't get any errors in the console, the rest of the script loads normally. I'm pretty new to mySQL and PHP, what am I doing wrong here? I suspect that I goofed up the php somehow.
XAMPP server, being tested on my desktop
all linked files are in the same directory
There are no visible errors displayed anywhere. As far as I can tell, the script doesn't even try to load the PHP to begin with, but also doesn't display an error in firebug's console
Attempted:
Renaming the table without spaces
placing the for loop inside the callback function
amending php errors
Here's the updated JS I'm using:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {"table" : "firstlist"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
and here's the updated PHP:
error_reporting(E_ALL); ini_set('display_errors','On');
$con = mysql_connect("localhost", "root", "m3648y73");
if (!$con){die('Could not connect: ' . mysql_error());};
mysql_select_db("tasklistdb", $con);
$table = $_GET['table'];
$sql = mysql_query("SELECT taskName, taskId, taskDescription, taskComplete FROM `".$table."`");
$listTasks = array();
while ($row_user = mysql_fetch_assoc($sql))
$listTasks[] = $row_user;
echo json_encode($listTasks);
mysql_close($con);
Am I linking to the DB correctly?

getJSON is asynchronous call. So before it could fetch values from PHP and execute the callback function, it moves to the for loop and here table is empty.
Solution: shift your for loop inside the callback function

You are missing a semi colon on the line $listTasks = array() in the php file

This happens because js-code after async request executed earlier than request itself is over. Try this:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {table : "first list"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}

Your table name can't be 'first list'
You can't have a space in a MySQL table name.
Also you should put put table in the JSON value in double-quotes like {"table":"table_name"}

Related

pass complex text to JQuery

I have ran into a strange behavior of passing JSON from PHP to jQuery.
I have some articles (Drupal CMS articles) and I need to push them into the environment.
First solution worked, while the articles was pushed directly by PHP on page load. But as my work works with more than one CMS, it takes too much time to load them all, so I need to use ajax to load one specific project at time.
now, jquery looks like this:
function doLoadArticles() {
for (var i = 0; i< projectdata[1].length; i++){
$.ajax({
data: {ip:projectdata[0]["ip"], login:projectdata[0]["login"], pass:projectdata[0]["pass"], db:projectdata[0]["db"], datatype:projectdata[1][i], aj:"aj", fc:"doLoadArticles"},
type: "post",
url: "dataFunnel.php",
success: function(data){
console.log(data);
//console.log(jQuery.parseJSON( data )) ;
}
});
}
}
Then, on PHP side is this code:
function doLoadArticles(){
$projdata;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("<div style='position:absolute; top:0;left:0; background:white;'>Connection failed: " . $conn->connect_error." <br><br>Plese try reload the page</div>");
break;
}
else{}
$sql = "Select node_revision.title, node_revision.nid, node.language, field_revision_body.body_value, field_revision_body.bundle, node_revision.timestamp
from field_revision_body
LEFT JOIN node_revision ON field_revision_body.revision_id=node_revision.vid
LEFT JOIN node ON field_revision_body.revision_id=node.vid
where field_revision_body.bundle='".$_POST['datatype']."' AND node_revision.status=1 AND node.language='cs'
ORDER BY field_revision_body.revision_id DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// error_log("true");
// output data of each row
$j =0;
while($row_a = $result->fetch_assoc()) {
$projdata[$j]["title"] = $row_a["title"] ;
$projdata[$j]["timestamp"] = $row_a["timestamp"] ;
$projdata[$j]["bundle"] = $row_a["bundle"] ;
$projdata[$j]["body_value"] = $row_a["body_value"];
$projdata[$j]["nid"] = $row_a["nid"];
$projdata[$j]["language"] = $row_a["language"];
$j++;
}
}
echo json_encode($projdata);
}
The problem is, that the data are there, only the passing itself does not work .. (probably because of some buged conversion?)
if I do
echo print_r($projdata);
it will pass the data, but not in usable way (ignore the broken chars, that is another not related problem, the data are thare, that is what matters)
However, as it is clear, I need it in form that I can work with, so I need json.
But if I use
echo json_encode($projdata);
it will pass some "broken nothing"
So is there any my mistake I am not aware of, or it is really some kind of bug in PHP implementation?
(by the way, I run on PHP 5.6 on MS IIS7)
Or any other way possible, how to load data dynamically without the json conversion?
Thanks in advance

How can i change a SELECT query using AJAX call

I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.

php database update not working

Basically i want to update my database with values from an array that i converted from javascript to php
then when a button is pressed it updates the database
i have this code but it doesnt update to the database
var v = document.getElementsByName('mark[]');
var arr = new Array();
for(var a=0; a<v.length; a++){
arr[a]=inputs[a].value;
}
var str;
for(var i=0; i<arr.length; i++) {
str+='&array_items[]='+arr[i];
}
document.location.href='./markandfeedback.php?'+str;
}
</script>";
for ($i=0; $i<count($_GET['array_items']); $i++){
$arr[] = $_GET['array_items'][$i];
}
if(isset($_POST['update'])){
$sql1="UPDATE `groupdatabase1` .`questions` SET `mark`= '".$arr[1]."',`studentID`= '4140001', `feedback` = 'meh' WHERE `questions`.`questionID`=1";
mysql_query($sql);
}
You are assigning your query to the variable named $sql1, but then using a different (probably uninitialized variable) named $sql in your call to mysql_query.
Well youre not sending a POST request youre sending a GET so $_POST['update'] will never exist. In addiiton to that im not sure why there is a " sfter the script tag... unless youre omitting code and thats actually written inside php theres no reason for it.
Typically you would use AJAX for this, otherwise you would use a form... even if you still run your JS and put the results in a set of hidden fields so there is no real form interface.

Titanium Appcelerator - How to Pull Remote Data

I'm using the following code to pull data and nothing happens. Here's my PHP CODE.
$getall = "SELECT * FROM pages WHERE account_id=$id ORDER BY course_id";
$showall = #mysqli_query ($dbc, $getall); // Run the query.
$json = array();
if (mysqli_num_rows($showall) > 0)
{
while ($row=$showall->fetch_assoc()) {
$json[]=array(
'logged' => true,
'pagename'=>$row['pagename'],
);
} // end while
header("Content-Type: text/json");
echo json_encode(array( 'pages' => $json ));
}
And here's my JS CODE that runs the app.
sendit.open('GET', 'http://myurl.com/mypages.php');
sendit.send();
sendit.onload = function(){
var json = JSON.parse(this.responseText);
var json = json.pages;
var dataArray = [];
var pos;
for( pos=0; pos < json.length; pos++){
dataArray.push({title:'' + json[pos].pagename + ''});
// set the array to the tableView
tableview.setData(dataArray);
};
};
var tableview = Ti.UI.createTableView({
});
currentWin.add(tableview);
When I run the app, all I get is a blank table. Any help would be greatly appreciated.
Have you tried to move sendit.send(); below sendit.open?
Put a log in your onload event to make sure it is being fired at all.
It states in the docs that the onload must be defined before you call open in order for that even to be registered.
You're embedding your array in another array, so on the javascript side it'd be:
dataArray.push({title:'' + json.pages[pos].pagename + ''});
^^^^^ - missing level
You should have sendit.onload before send it.send.
I would also recommend you to implement sendit.onerror method, as well as intermediate Ti.API.debug(stuff);
You also double the declaration of json, with is working, but not great.

Passing array with ajax - can't print

I hope this problem is very simple, I can't figure out the solution myself it seems. Been trying and googling for hours, driving me nuts :) Ok, so I have a drag'n'drop + sortable (using scriptaculous and prototype for your information) on my index.php. I use this code to send the items dropped in a div using this code:
<script type="text/javascript">
//<![CDATA[
document.observe('dom:loaded', function() {
var changeEffect;
Sortable.create("selectedSetupTop", {containment: ['listStr', 'selectedSetupTop'], tag:'img', overlap:'vertical', constraint:false, dropOnEmpty: true,
onChange: function(item) {
var list = Sortable.options(item).element;
$('changeNotification').update(Sortable.serialize(list).escapeHTML());
if(changeEffect) changeEffect.cancel();
changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" });
},
onUpdate: function(list) {
new Ajax.Request("script.php", {
method: "post",
parameters: { data: Sortable.serialize(list), container: list.id }
onLoading: function(){$('activityIndicator').show(), $('activityIndicator2').hide()},
onLoaded: function(){$('activityIndicator').hide(), $('activityIndicator2').show()},
});
}
});
});
// ]]>
</script>
I've been using this code before so I "kind of know" it will send me data to my script.php page. selectedSetupTop is my div containing the elements. Don't mind about the notification and the activityIndicator thingy. My script.php page looks like this for the moment:
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$test .= $selectedSetupTop[$i];
}
echo "<script>alert('$test');</script>";
I can't seem to get any output in the alert message, it's just blank. The purpose of the script.php is to update a row in a database and it will look kind of like this:
$sql = mysql_query("UPDATE table SET row = '$arrayInStringFormat' WHERE id = '1'") or die(mysql_error());
where the $arrayInStringFormat is a conversion of the array $selectedSetupTop to the format (1, 2, 3, 4). I guess I'll solve that using implode or something, but the problem is parsing the array $selectedSetupTop. I'm not it passes between the pages at all, really appreciate help! Tell me if I need to explain further.
Thanks in advance!
''''''
EDIT 1
If it will help, I used this code before that I know will send me the data and use it. Notice I don't wanna do my task like the way I do below:
$querySetup = $_GET["s"];
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$sql = mysql_query("UPDATE " . $querySetup . " SET orderId = $i, hero_selected = 'n' WHERE imageId = $selectedSetupTop[$i]") or die(mysql_error());
}
''''''
EDIT 2
So it does parse, but I still have the problem I can't print it. I wanna implode the array somehow.
Not sure how AJAX works in Scriptalicious/Prototype, but you don't seem to be getting the data from the AJAX call. In jQuery it would be something like this where the data you receive from the script is returned as the argument of the function.
onLoaded: function(msg){
$('activityIndicator').hide(),
$('activityIndicator2').show(),
alert(msg)
}
Secondly, you can't echo a PHP array, you have to encode it to JSON:
echo json_encode($test);

Categories