filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);
Related
I am using this rss.php file for rss feed but the problem is that it shows feed from just 2 tables not all the 4.Where is the problem?Feed is coming from famous people and econmicsandpolitics table only.
<?php
function connect() {
return new PDO('mysql:host=localhost;dbname=wg','root','', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$myarray = array('scienceandtechnology','economicsandpolitics','famouspeople','yetosbkistoryhe');
$key = array_rand($myarray);
$table= $myarray[$key];
$sql = "SELECT * FROM ".$table."";
$query = $pdo->prepare($sql);
$query->execute();
$rs_post = $query->fetchAll();
// The XML structure
$data = '<?xml version="1.0" encoding="UTF-8" ?>';
$data .= '<rss version="2.0">';
$data .= '<channel>';
$data .= '<title>google</title>';
$data .= '<link>http://www.google.com</link>';
$data .= '<description>io</description>';
foreach ($rs_post as $row) {
$data .= '<item>';
$data .= '<title>'.$row['title'].'</title>';
$data .= '<link>'.$row['content'].'</link>';
$data .= '<description>'.$row['summary'].'</description>';
$data .= '</item>';
}
$data .= '</channel>';
$data .= '</rss> ';
header('Content-Type: application/xml');
echo $data;
?>
You are here using it statically from table names i have almost same kind of problem but in my case the table name is also dynamic So use it according to your relevance
$sql = mysql_query("select name from sections order by rand()");
$datadisplay = array();
while ($row= mysql_fetch_assoc($sql)){
$section=$row['name'];
$sqldata = mysql_query("select title,summary from ".$section." order by ID limit 2");
while ($rowdata= mysql_fetch_assoc($sqldata)){
$datadisplay[] = $rowdata;
}
}
so here what i am doing is i fetching table names from sections and after that using those table names to fetch data from table and then storing that data into another array which then can be used to get rss data
If I understand correct it may help you ,
$pdo = connect();
$myarray = array('scienceandtechnology','economicsandpolitics','famouspeople','yetosbkistoryhe');
foreach ($myarray as $table) {
$sql = "SELECT * FROM ".$table."";
$query = $pdo->prepare($sql);
$query->execute();
$rs_post = $query->fetchAll();
foreach ($rs_post as $post) {
// echo something
}
}
I am making a call to php file, which is picking up data of 'name' and 'email' row-by-row and need to send it as a ajax response to my index.html file. I can fetch the row data but unable to know, how to send back the data as a reply to ajax request in json form.
PHP Code:
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
echo "jname".$row["name"]."jemail".$row["email"];
}
}
else{
echo "0 results";
}
Instead of just echoing out the data as you are, store it in an array and use json_encode to return it as a json string.
$return = array();
if ($result->num_rows > 0){
$return['result'] = $result->num_rows.' results';
$return['rows'] = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$return['rows'][] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
else{
$return['result'] = "0 results";
}
echo json_encode($return);
Put your result in array, and print it via json_encode()
$response = array();
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$response[] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
echo json_encode($response);
exit();
I made the following script but I want that each script should echo the json_encode array only when I call the function. When I tried defining the function, and then calling it, it displayed nothing. It is working if the scripts are not made in the functions. How do I make different functions and then call different functions according to my usage?
<?php
ini_set('display_errors', '0');
error_reporting(0);
require_once("include/db.php");
date_default_timezone_set('Asia/Kolkata');
$regno ='14ASDFJ234';
$password = '0';
$name = 'EASPORTS';
$priority = 0;
//fetch priority
$query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
if($found)
{
$priority=$found['priority'];
}
//echo $priority;
echo 'news feed : <br> '
$sql = "SELECT * FROM newsfeed";
$result = mysql_query($sql,$conn) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$details[] = array(
'name' => $row['name'],
'feed' => $row['feed']
);
}
echo json_encode($details);
// announcement details...
echo "<br> Announcement details: <br>";
$sql1 = "SELECT * FROM announcements WHERE name = '$name'";
$result1 = mysql_query($sql1,$conn) or die(mysql_error());
while ($row1 = mysql_fetch_array($result1)) {
$details1[] = array(
'name' => $row1['name'],
'pname' => $row1['pname'],
'date' => $row1['date'],
'time' => $row1['time'],
'status' => $row1['status']
);
}
echo json_encode($details1);
//events script...
?>
You should do like this
public function somefunction()
{
$query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
if($found)
{
$priority=$found['priority'];
}
//echo $priority;
echo 'news feed : <br> '
$sql="SELECT * FROM newsfeed";
$result=mysql_query($sql,$conn) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$details[] = array(
'name' => $row['name'],
'feed' => $row['feed']
);
}
echo json_encode($details);
}
now when you call somefunction() you will get json encoded array as result
I'm a beginner in using PHP and Javascript, and I don't have any idea on how to store the data that I've gathered from MySQL which I placed in a multidimensional array in PHP to a 2D array in Javascript. Here's my working code in PHP:
<?php
function connecToDatabase(){
$host = "localhost";
$username = "root";
$password = "p#ssword";
$database = "flood_reports";
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
}
function retrieveData(){
connecToDatabase();
$data = mysql_query('SELECT * FROM entries') or die(mysql_error());
$entries = array();
$index = 0;
while($info = mysql_fetch_array( $data ))
{
$entries[$index] = array('entry_id' => $info['entry_id'],
'location' => $info['location'],
'image_dir' => $info['image_dir'],
'longitude' => $info['longitude'],
'latitude' => $info['latitude'],
'level' => $info['level']);
$index++;
}
$json = json_encode($entries);
echo $json;
mysql_close();
}
retrieveData();
?>
on the end of your script add the following
<script type="text/javascript">
var jsvar = <?php echo $phpvar;?>
</script>
Replace
echo $json;
with
echo 'var fromPhp = ' . $json . ';';
You just need to put the data into a variable. This will make it available as fromPhp on the browser side.
I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch