I'm trying to create a php page that should shows me a json output.. I'm in a wordpress website and maybe it's a little bit different to retrive datas from database than in a normal php page. By the way, this is my code:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
global $wpdb;
$code = '';
$code=$_REQUEST['code'];
$timestamp = '';
$timestamp=$_REQUEST['timestamp'];
$username = '';
$username=$_REQUEST['username'];
$selectData = "SELECT * FROM protocol_data_list WHERE username = '$current_user->user_login'";
//Create an array
$json_response = array();
$result = $wpdb->query($selectData);
echo $result;
while ($row=mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo $row;
$row_array['code'] = $row['code'];
$row_array['timestamp'] = $row['timestamp'];
$row_array['username'] = $row['username'];
array_push($json_response,$row_array);
}
$json_response = str_replace('\\/', '/', json_encode(array('item' => $json_response), 128));
echo $json_response;
?>
this kind of code is the one i use always to create a json.. But in wordpress it returns an empty array.. I don't know if something's wrong.
Related
the following code is only running once , while the number of times it should run is 4 , any help ?
PHP::
<?php
header("Content-Type: application/json");
require_once("config.php");
if(isset($_GET["m"])) {
$dirname = "images/main/";
$arr = array();
$conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if(!$conn) {
echo "Error connecting to database";
exit();
}
if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
$stmt->execute();
$stmt->bind_result($n);
//$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0) {
echo "No Projects";
$stmt->close();
$conn->close();
exit();
}else {
while ($row = $result->fetch_assoc()) {
$dirname = $dirname . $row["name_"] . "/";
$images = glob($dirname . "*.*", GLOB_BRACE);
foreach($images as $image) {
echo $row["name_"];
echo$result->num_rows; // returns 4 !!!!
$image = base64_encode($image);
//$arr[] = $image;
array_push($arr, $image);
$image = "";
}
}
echo json_encode($arr); // returns 1 json row oonly
}
}
$stmt->close();
$conn->close();
exit();
}
?>
num rows return 4 so why it runs or loops for one time only ?
I am trying to get images from images folder to echo it back
FIX::
according to jhilgeman's answer I added this part to the end of foreach:
$dirname = "images/main/";
If I had to guess, I'd say that it's looping correctly, but the problem is this line:
$dirname = $dirname . $row["name_"] . "/";
Each time you loop, you're APPENDING the $row["name"] value to whatever $dirname is. So let's say that you get 4 rows back like this:
name
----
houses
boats
computers
animals
At the beginning of the loop, let's say $dirname is just "/images/". So the first loop would change $dirname to be:
/images/houses/
Then the second loop would change it to be:
/images/houses/boats/
The third loop would then make it:
/images/houses/boats/computers/
And finally the fourth loop:
/images/houses/boats/computers/animals/
So unless you're expecting the $dirname to be appended that way, you probably want to instead REPLACE $dirname instead of appending to it each time.
Try this instead for your loop:
while ($row = $result->fetch_assoc()) {
$images_dirname = $dirname . $row["name_"] . "/";
$images = glob($images_dirname . "*.*", GLOB_BRACE);
foreach($images as $image) {
...etc...
}
}
I'm trying to return a row from my database however, when I replace the page='url' with $filePath = $_SERVER["REQUEST_URI"]; page='.$filePath.' it returns nothing.
I'm assuming the answer is simple however, I can't see to find the solution.
Full Code
$filePath = $_SERVER["REQUEST_URI"];
$query = "SELECT * FROM Meta WHERE page=' . $filePath . '";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) { ?>
<title><?php echo $row["title"]; ?></title>
<?php } ?>
try the query like this
$query = "SELECT * FROM Meta WHERE page = '" . $filePath . "' ";
This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);
i created a script that connects to my database called mysqlconnecter:
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "pass");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}
?>
And then I created another script that includes mysqlconnecter.php and posts the data inside the database:
<?php
include "mysqlconnecter.php";
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
?>
but the output displays the data inside the database twice:
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
I only want it displaying the text once,
What do I do?
Your logic is slightly the wrong way round.
This is because your loop is finished then you are echoing the data so it will always be the last row.
You need to echo whilst in the loop or create an array then loop the array later.
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
//this will echo for EVERY row the loop iterates.
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
}
For your double output i suspect you have included the file twice. But thats guessing as i don't see all of your code.
If you want to keep the display code outside your mysqlconnecter.php file, you could do this in your loop:
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = array(
'id' => $row['member_id'];
'username' => $row['username'];
'password' => $row['password'];
'rank' => $row['rank'];
}
And then in your script:
include "mysqlconnecter.php";
foreach ($data as $key => $value)
{
echo 'ID = ' . $value['id'] . '<br>';
// etc
}
For your "double print" problem, I would try to put a var_dump($data); right after your while() in mysqlconnecter.php, to see what happens exactly.
If the var_dump display correctly reflects the expected result of your query, the problem is elsewhere, possibly that you include mysqlconnecter.php twice, as Dave suggested. To be sure it's included only once throughout your whole code, simply replace include() with include_once().
Are you sure you don't have any mistake? is that all code you show us?
Because logically your script will print once and will print the last data from your members table
I have try it
I am making an email script in php. What happens is a mysql query is made, and the output of this is stored in the following strings :
$personal1 = $userinfo->salutation;
$personal2 = $userinfo->surname;
$business = $userinfo->businessname;
Next I have an if statement, this checks to see if the surname is blank, if it is, it then substitutes the salutation + surname with the business name. The problem I am having is that the emails keep being sent out with Dear, Business Name , even if the surname field is not blank, I am not sure what I am doing wrong with the following code for it to do this though ?.
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
EDIT >>>>>>>>>>
If I echo out the contents of the strings I get :
personal1 = Mr
personal2 = Johnson
business = Hat Trick Media
Edit 2 >>>>>>>
This is some of the code, it is then passed onto the mailer.
<?php
$cf_uid = $_GET['token'];
$query = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead WHERE cf_uid = '$cf_uid'") or die(mysql_error());
$userinfo = mysql_fetch_object($query);
$personal2 = $userinfo->surname;
$personal1 = $userinfo->salutation;
$business = $userinfo->businessname;
?>
<?php
$result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addemailtemplate");
while ($row = mysql_fetch_object($result)) {
echo '<tr class="table-row">';
echo '<th class="template-name">';
echo '<div class="namerow">';
$id = $row->cf_uid;
$form_id = $row->form_id;
$query = mysql_query("SELECT `$form_id` FROM email_history WHERE cf_id = '$user_id'") or die(mysql_error());
$datesent = mysql_fetch_object($query);
$date = $datesent->$form_id;
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Is your code a valid statement? Your code structure is awful. Instead of...
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Use
if ($personal2=="") {
$name = $business;
}
else {
$name = $personal1 . ' ' . $personal2;
}
You seem to have an extra ; that you dont need.
You also dont seem to close the while loop in the code you posted...
Ok, I have found out what the problem was, $name was coming in the session from the previous page and overwriting $name on this page, I have now set it to destroy the session before it loads this page and it seems to have sorted it now, thanks for everyone's help :-)