How to get print on browser console using PHP - php

I am testing out my php code and want to make see the files that I am getting from json and check how it is displaying so I know how to send the code to mysql
php file
<?php
$json = json_decode(file_get_contents("php://input"));
$obj = json_decode($json,true);
print_r($json);
print_r($obj);
function debug_to_console( $data ) {
$output = $data;
if ( is_array( $output ) )
$output = implode( ',', $output);
echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}
debug_to_console( "Test" );
debug_to_console($obj);
print_r("hello");
echo "<script>console.log('" . json_encode($json) . "');</script>";
echo "<script>console.log('" . $obj . "');</script>";
echo "<script>console.log('" . '$obj' . "');</script>";
var_dump('Hello');
var_dump($obj);
var_dump($json);
header("Content-Type: application/json; charset=UTF-8")
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
None of this prints to the console
Want code to print to the console

You can try the following function
function consoleLogs($data) {
$html = "";
$coll;
if (is_array($data) || is_object($data)) {
$coll = json_encode($data);
} else {
$coll = $data;
}
$html = "<script>console.log('PHP: ".$coll."');</script>";
echo($html);
}
You can use this as :-
consoleLogs(array("test1", "test2"));

Related

How to print out individual field data on the page instead of the entire table contents

So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.
From the code below, i need help on how I can print something like this:
echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
This is the code I need to be modified :
<?php
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
}
echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Just like you normally would print results of SELECT query. Although here it seems there's an ajax call invovled.
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
$result = null;
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
$result = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
$result = $products;
}
// echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
$html = "";
foreach ($result as $row) {
$html .= "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
}
// return as HTML (won't work in ajax)
echo $html;
// or for ajax:
echo json_encode($html, JSON_PRETTY_PRINT) . "\n";
// or
echo json_encode(["html" => $html], JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}

Php code to get json data from mysql database

Iam trying to create a JSON object out of my SQL data in PHP. How to do that?
This is my approach, which does not work so far.
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros = "[";
while ($result = $query->fetch()) {
if ($registros != "[") {
$registros .= ",";
}
$registros .= '{"id": "' . $result["id"] . '",';
$registros .= '"name": "' . $result["name"] . '"}';
$registros .= '"salary": "' . $result["salary"] . '"}';
$registros .= "]";
echo $registros;
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>`
Why dont you try the json_encode() for this ? Why you try for unnecessary while loop.
$query = $conn->prepare('SELECT id, name, salary from afreen');
Then try the json_encode() to get the Data in Json format.
Sources - http://php.net/json_encode
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros= [];
while ($result = $query->fetch()) {
array_push($registros,array(
'id' =>$result["id"],
'title' =>$result["name"],
'salary' =>$result["salary"]
));
$output = json_encode(array("product"=>$registros));
print_r($output);
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>

Give argument php function to show database results in another file

I have this php code to connect database it works fine.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cv";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM services";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
My question is: how to create function getServices() and give argument to show this results in another php file using foreach or while, like this:
<?php foreach ($results as $key=>$result) : ?>
<?php echo $result['service_name']; ?>
<?php endforeach; ?>
Okay. So you have to do the following things:
db.php :
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cv";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function yourFunctionName() {
$sql = "SELECT * FROM services";
$result = $conn->query($sql);
return $result;
}
$conn->close();
otherfile.php :
<?php
include 'db.php';
$data = yourFunctionName();
if ($data->num_rows > 0) {
// output data of each row
while($row = $data->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>";
}
} else {
echo "0 results";
}
?>
Hope this works, haven't tested yet.

Fatal error: Call to a member function fetch_assoc() on string

I tried to execute a query and iterate thru the result. The echo "<h1>" . $row["SummonerId"]. "</h1>"; works and it print it out at the page. But somehow this Error occurred after the printed result:
Fatal error: Call to a member function fetch_assoc() on string
I saw many errors similar to this. But those are on a non-object and not on string. What is that error?
Here is my code:
$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h1>" . $row["SummonerId"]. "</h1>";
$summonerId = $row["SummonerId"];
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;
$result = file_get_contents($url);
$resultJSON = json_decode($result);
foreach($resultJSON_decoded->games as $game){
echo $game->gameMode." ".$game->gameType." ".$game->subType;
echo "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
$result variable is used to loop thru mysql query, you have to use different variable names inside your loop
$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h1>" . $row["SummonerId"]. "</h1>";
$summonerId = $row["SummonerId"];
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;
$fcontents = file_get_contents($url);
$resultJSON = json_decode($fcontents);
foreach($resultJSON_decoded->games as $game){
echo $game->gameMode." ".$game->gameType." ".$game->subType;
echo "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
One more little thing I noticed.. $resultJSON and $resultJSON_decoded doesn't match inside the loop

String to Integer Returning 0

I am converting , through type cast , through intval() and other procedures , but what is returned from $Id (string :eg "99973132") is always 0. I will be grateful if anyone can guide me.The value that I am converting from string to int is of length 99973132(all the values are close to this) . I have crossed checked . The value returned in $Id is 99973132 but conversion results in 0
<?php
require_once('../SchemaBuilder/Dbconfig.php');
require_once('../SchemaBuilder/NativeConfiguration.php');
$servername = MYSERVERNAME;
$username = MYUSERNAME;
$password = MYPW;
$dbname = MYDBNAME;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!file_exists($_FILES['csvdata']['tmp_name']) || !is_uploaded_file($_FILES['csvdata']['tmp_name']))
{ echo "no file";
echo "<br> No file Selected press back to try again!!<br>";
}
else
{
$content= file_get_contents($_FILES["csvdata"]["tmp_name"]);
$content= file_get_contents($_FILES["csvdata"]["tmp_name"]);
$lines = explode("\n", $content);
$i = 0;//initialize
foreach($lines as $value)
{
if($i != 0)
{
$cols[$i] = explode("\t", $value);
if(isset($cols[$i][9]))
{ $id=$cols[$i][0] +0;
$query = "INSERT INTO csvdata(Id,UserName)
VALUES(".$i.", '".$cols[$i][9]. "')" ;
if ($conn->query($query) === TRUE)
{
echo "New record created successfully".'<br>';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error.'<br>';
}
$x++;
}
}
$i++;
}
$conn->close();
}
?>
Edit : I am loading a .tsv file , after that parsing each line by skiping first line , then exploding by \t . fetching first attribute which is in $id and converting it to integer . but its not converted and gives 0

Categories