I have a mysql database table called 'employees'
It has 3 columns named 'id', 'name' and 'salary'
I have html/php web page with text boxes called id and name.
I want to load 'id' and 'name' of the employee who has the maximum salary, from database to these text boxes.
<?php
//Defining constants for database connection best to store in seperate file and include that file
const DB_HOST = 'SERVER';
const DB_USER = 'USER';
const DB_PASS = 'PASSWORD';
const DB_NAME = 'php_mysql_login_system';
//Connecting to the database -- best use pdo
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$sql = " SELECT * from `employees` "; // query data from databse -- alhough I suggest you use pdo
$result = $mysqli->query($sql);
//Looping through each results
foreach ($result as $value) {
// Store the employess salary and name in an array say employee['name'=>salaray] -- name as key and salary as value
}
$maximumSalary = max(//array of the employee i.e the one you have made above employee[]);
//after getting the maximum value use array_keys(array,value) to get the employee name
$employeeName = array_keys($employee,$maximumSalary);
}
?>
A sample code to get you started hope this helps you although this code might not be following best practise it is for you to get started with at least something as I think you are having trouble getting started.
Related
This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I have a mysqli query which I need to format as JSON for a mobile application.
I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)
$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);
// create xml format
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);
// add node for each row
while($row = $stmt->fetch()) :
$occ = $doc->createElement('data');
$occ = $root->appendChild($occ);
$child = $doc->createElement('section');
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);
endwhile;
$xml_string = $doc->saveXML();
header('Content-Type: application/xml; charset=ISO-8859-1');
// output xml jQuery ready
echo $xml_string;
Simply create an array from the query result and then encode it
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
$result = $mysqli->query("SELECT * FROM phase1");
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
output like this:
[
{"id":"31","name":"product_name1","price":"98"},
{"id":"30","name":"product_name2","price":"23"}
]
If you want another style, you can change fetch_assoc() to fetch_row() and get output like this:
[
["31","product_name1","98"],
["30","product_name2","23"]
]
Here's how I made my JSON feed:
$mysqli = new mysqli('localhost', 'user', 'password', 'myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
As mentioned, json_encode will help you. The easiest way is to fetch your results as you already do it and build up an array that can be passed to json_encode.
Example:
$json = array();
while($row = $stmt->fetch()){
$json[]['foo'] = "your content here";
$json[]['bar'] = "more database results";
}
echo json_encode($json);
Your $json will be a regular array with each element in it's own index.
There should be very little changed in your above code, alternativly, you can return both XML and JSON since most of the code is the same.
There is one essential thing about JSON - the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.
The rest is as silly as any other database operation
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$db->set_charset('utf8mb4');
$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $db->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);
I managed to run this code:
<?php
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
If you have mysqlnd extension installed + enabled in php, you can use:
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$result = $mysqli->query("SELECT * FROM phase1");
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
mysqli::fetch_all() needs mysqlnd driver to be installed before you
can use it.
I'm trying to return a JSON object with a Key,Value pair, both of which are seperate columns in my MySQL table.
So the MySQL table Looks (simplified 1000%) like this:
+-----------------+---------------------+
| Email | ProfilePicture |
+-----------------+---------------------+
| john#email.com | https://someurl.com |
| jane#email.com | https://foobar.com |
| bobby#email.com | https://random.com |
+-----------------+---------------------+
And I want a JSON object like
{
"john#email.com":"https://someurl.com",
"jane#email.com":"https://foobar.com",
"bobby#email.com":"https://random.com"
}
I could build it up as a string in MySQL by looping through the table and concat everything together, then just parse it in JS. I know that. But it seems messy, and I know there must be some built in functions for this in PHP. I just don't know them.
All my other PHP/MySQL pairings are using mysqli_fetch_assoc and json_encode in the PHP as they don't need the JSON Key to change dynamically only the value.
The eventual JSON object is being returned from a JavaScript function, so I am happy with a fix any where along the chain from JavaScript (or jQuery), to PHP, to MySQL Procedure, and back along.
If you use PDO to connect the database, you can use something like...
$query = $db->query("SELECT Email, ProfilePicture FROM users");
$data = $query->fetchAll(PDO::FETCH_KEY_PAIR);
$out = json_encode($data);
The PDO::FETCH_KEY_PAIR uses the first column returned as the key and the second column as the value.
Sticking to mysqli
$result = $db->query("SELECT Email, ProfilePicture FROM users");
$data = [];
while ($row = $result->fetch_assoc()) {
$data[$row['Email']] = $row['ProfilePicture'];
}
$out = json_encode($data);
MySQLi version - slightly shorter...
$result = $db->query("SELECT Email, ProfilePicture FROM users");
$data = $result->fetch_all(MYSQLI_ASSOC);
$out = array_column($data, 'ProfilePicture', 'Email');
$out = json_encode($data);
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
this is the code i have, actually i am inserting a array in json encode data and getting back via jquery.
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
while($r = mysqli_fetch_array($query)){
$result_value = array("Status" => "haslist", "list" => $r);
}
this is jquery side.
case "loaddefaultmodel":
var showtype = $('#sh');
var showvalue = '<span>'+data['list']+'</span>';
showtype.html(showvalue);
break;
$('#sh') is a div i need to show all type content in the span inside the div.
if i use the data['list'][0]['type'] i getting a object 0 value.
how to show all value one by one dynamically in div.
I think the issue in your php code.
Because in every loop, the $r just get every current index data, And $result_value just get current index data.
You can try this...
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
$all_data = array();
while($r = mysqli_fetch_array($query)){
$all_data[] = $r;
}
$result_value = array("Status" => "haslist", "list" => $all_data);
This question has been asked earlier too, but no body has answered I guess.
Lets say mysql query returns result like following
name | id
tarun | 1
tarun | 2
tarun | 3
Now If we do standard json encode, I will get some thing like below:
[{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}]
But I was output something like below
[{"name" : "tarun", "ids" : [{"id": "1"},{"id": "2"},{"id": "3"}]}]
Please ignore my syntax mistakes (if any), But I hope my ques makes sense.
I am using PHP as my backend scripting language.
You're probably doing something like
SELECT name, id FROM ...
and
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Given your desired structure, you'd want
$data[$row['name']]['ids'][] = array('id' => $row['id']);
This won't give you your exact structure, but it would be put all the ids as a child-array beneath an array keyed by the tarun field value.
Extending #Marc B's answer
// Getting per person id's list
$people = array();
while ($row = mysql_fetch_assoc($result)) {
$people[$row['name']][] = array('id' => $row['id']);
}
// Encoding as JSON
$output = "[";
foreach ($people as $name => $ids) {
$output .= '{"name" : "'.$name.'", ids: [';
foreach ($ids as $key => $id) {
$output .= '{"id" : "'.$id.'"},';
}
rtrim($output, ",");
$output .= ']},';
}
rtrim($output, ",");
$output .= ']';
echo $output;
The solution above is specific to the question. A generic JSON Encode method for this problem in my opinion is very tough or not possible.
I suggest to do the query with orderying by name, then when you read the rows, just do a simple check to see if the $row['name'] has changed, if so add the id's youve collected to the php object.
$curName="";
$curIds=array();
$betterJ=array();
$result = mysql_query ("SELECT name,id FROM mytable WHERE 1 ORDER BY NAME);
while($row=mysql_fetch_array($result)
{
if($curName=="")
$curName=$row['name']
if($row['name']!=$curName){
$betterJ[]=array($name=>$curName,$ids=>$Ids)
$curName=$row['name']
$curIds=array()
}
$Ids[]=$row['id];
}
$betterJ[]=array($name=>$curName,$ids=>$Ids);
echo json_encode($betterJ);
this might have a typo or something since I wrote it here, but it should produce json like
[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]
which you would work great in a template in html etc.