I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}
Related
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
*fixed****
echo "<li>" . $row['iname'] . "</li>";
what is missing ?
.php
/facepalm
I can't seem to get the id value to pass to the $_GET. I've tried adding sessions and all kinds of stuff.
Even when I just do a print_r($GET) by itself it gives me :
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete
This is not for production, but a project so I'm not to worried about injections ect..
I've use GET with old php mysql syntax and it works, just not sure what the problem is. Alos no the code is barbaric so any help would be greatly appreciated.
Page 1 :
<?php
require('lib/inc/db_inc.php');
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE items.itype = 'usb_controllers'";
$stmt = $db->query($sql);
while ($row = $stmt->fetch()){
$id = $row['itemID'];
echo "<div class=\"prodMain\">";
echo "<div class=\"img\">";
echo "<img src=\"" . $row['imgURL'] ."\"/>";
echo "</div>";
echo "<ul>";
echo "<li>" . $row['iname'] . "</li>";
echo "<li>" . $row['idesc'] . "</li>";
echo "<li>" . $row['iprice'] . "</li>";
echo "</ul>";
echo "</div>";
}
?>
page 2 :
<?php
require('../lib/inc/db_inc.php');
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
$row = $stmt->fetch();
echo print_r($row);
?>
db_inc.php
<?php
try {
$db = new PDO('mysql:host=******;dbname=*****', '*********', '********');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
This statement
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
has a vulnerability for SQL Injection. See here.
So you should rewrite it like
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
So I have this PHP code:
Note: I do use mysqli_connect() further up.
$result = mysqli_query($con,"SELECT * FROM `smf_messages` WHERE `id_board` = 18");
if(!$result) {
echo "<center><p>Couldn't fetch news posts. Error code 2.</p></center>";
mysqli_close($con);
} else {
$posts = array();
$topicbdy = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$posts[$row['id_topic']] = $row['id_topic'];
$topicbdy[$row['id_msg']] = $row['id_msg'];
}
$display = max($posts);
$display2 = min($topicbdy);
$qry = "SELECT * FROM `smf_messages` WHERE `id_board` = 18 AND `id_topic` = " . $display . " AND `id_msg` = " . $display2;
$result2 = mysqli_query($con,$qry);
//echo $qry;
if(!$result2) {
echo "<center><p>Couldn't fetch news posts. Error code 3.</p></center>";
} else {
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<center><h1>" . $show['subject'] . "</h1></center><br /><br />";
echo "<center>" . $show['body'] . "</center><br />";
}
}
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_close($con);
It's supposed to get the latest topic out of the database for my SMF-based forum from the news board, by getting the highest topic id, but the lowest post id. It seems to be doing the query just fine, as I don't get any errors, but it doesn't show the subject or body. What should I do?
Your $result variable is wrong for second query fetch. For your second query
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
Should be
while($show = mysqli_fetch_array($result2,MYSQLI_ASSOC))
^
i Have This PHP and JS Code on my web page.
<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
echo "<script type='text/javascript'>";
echo "this.styleListArray = new Array();";
if ($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
$counter += 1;
}
}
echo("</script>");
?>
The Problem is that when i execute the page containing the code, a part of this code doesn't get executed and it just shows on the page as a simple text :
"); echo "this.styleListArray = new Array();"; if ($result) { while($row = mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?>
I tried to figure it out, but i couldn't get it, if you can help brothers, that would be wonderful.
Try rewriting your code like this:
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array
echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;
$strLine = '';
if ($result) {
while($row = mysql_fetch_array($result)) {
$strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';";
$counter += 1;
}
}
echo $strLine;
echo("</script>");
First of all change your queries to use mysqli or pdo connections
secondly try following code
$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
$rows[] = $row['URL'];
$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';
echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';
check you console log.
You have $result = mysql_query($query) or die (mysql_error());; change it to
$result = mysql_query($query) or die (mysql_error());
Also make sure $row['URL'] and $row['user_fname'] are available.