The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}
Related
I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer
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.
Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();
Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';
I'm pretty new to php, and I'm teaching myself. I've looked at a few different resources, and the php script I have now doesn't return any critical errors when executed, but its not returning the data from the table.
<?php
$connect = mysqli_connect("localhost","*","*","*");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$comments = "SELECT * FROM commentstable";
$rs = mysqli_query($connect,$comments);
$fetch = mysqli_fetch_array($rs);
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
echo $fetch;
mysqli_close($connect);
echo "hello";
?>
you have double entry:
$fetch = mysqli_fetch_array($rs); //<--- remove this as you are calling it again in the while loop
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
Check this
$connect = mysqli_connect("localhost","turlough","samus1","comments");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$comments = "SELECT * FROM commentstable";
$rs = mysqli_query($connect,$comments);
if($rs)
{
while($fetch = mysqli_fetch_array($rs)) {
echo $fetch['comments'];
}
}
else
{
// no results from query
}
mysqli_close($connect);
}