I'm currently working on a project where I need to get some data from 3 different tables out of a database and echo them so I can work with the results in jQuery. I'm sending a GET-request with 3 variables to my PHP. The first one is used to determine which 'command' needs to be executed, the other 2 are used to determine which table and which row needs to be queried.
This is the code I have so far:
} elseif($_GET['command']=='getpage') {
$mypid = $_GET['id'];
$mytable = $_GET['table'];
$link = mysqli_connect($dbserver,$userdb,$passdb,$db_typo) or die(mysqli_error($link));
if($mytable == 'tableName1'){
$query = 'SELECT * FROM table1 WHERE uid = "'.$mypid.'"'; //I need 6 elements from this table
} elseif($mytable == 'tableName2'){
$query = 'SELECT * FROM table2 WHERE uid = "'.$mypid.'"'; //I need 7 elements from this table
} elseif($mytable =='tableName3'){
$query = 'SELECT * FROM table3 WHERE uid = "'.$mypid.'"'; //I need 8 elements from this table
} else {
echo 'no such table supported for this command';
}
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$pagecontent = array();
while($row = mysqli_fetch_assoc($result)){
$pagecontent[] = array(
'id' => utf8_encode($row['uid']),
'name' => utf8_encode($row['name']),
'text1' => utf8_encode($row['text1']), //not every table has this
'text2' => utf8_encode($row['text2']),
'img' => utf8_encode($row['image']),
'parent' => utf8_encode($row['parent']), //not every table has this
'sub_parent' => utf8_encode($row['sub_parent']), //not every table has this
'deleted' => utf8_encode($row['deleted'])
);
}
echo '{"content": '.json_encode($pagecontent).'}';
}
I have over 50 pages which I need to get from the database. So when I would let the jQuery function that sends the GET-request run trough I would end up spamming the error.log with
PHP Notice: Undefined index: text1 in /var/www/my.php on line 171
which I don't want.
Is there another way to fix this 'problem' than just putting the query and while-loop inside the if-statement?
I don't know whats the reason of why don't you want an if to check for indices, but you could add another loop inside the while
and add those variables:
while($row = mysqli_fetch_assoc($result)){
$temp = array();
foreach($row as $key => $value) {
$temp[$key] = utf8_encode($value);
}
$pagecontent[] = $temp;
// $pagecontent[] = array_map('utf8_encode', $row);
}
echo json_encode(array('content' => $pagecontent));
This just simply gets all the contents inside your $row
, encodes all values then push it inside your container.
Sidenote: Don't build the JSON string by hand, create the final array structure, then encode in the end.
Add a check whether an array key exists
'text1' => isset($row['text1']) ? utf8_encode($row['text1']) : '',