get values as array - php

$sql=mysql_query("select cost from projectdetails");
while($row=mysql_fetch_assoc($sql))
{
$data=$row['cost'];
}
This is my php code Can you help me how to get like this,,
$data = array("0" => 898, "1" => 1498, "2" => 1343,"3" => 1345, "4" => 1045, "5" => 1343, "6" => 987);

Just $data[] = $row['cost']; and you'll get $data as an array

Try this:
$count = 0;
$sql=mysql_query("select cost from projectdetails");
while($row=mysql_fetch_assoc($sql)) {
$data[$count]=$row['cost'];
$count++;
}

First of all you should use PDO, its much better, try this
//edit for your server/database
$username = "username";
$password = "password";
$hostname = "hostname";
$dbname = "database-name";
//to connect to the database
$db = new PDO('mysql:host='.$hostname.';dbname='.$dbname.';charset=utf8', $username, $password);
Then the query is very simple
$query = "SELECT cost FROM projectdetails;";
$sth = $db->prepare($query);
$sth->execute();
$data = $sth->fetchAll();
And now you have all your $data as an array, you can loop through it, assign different values or whatever you want.

Related

How do I store the results of the for loop as an array in the res variable?

I want to store the results of the for loop as an array in the variable
$res. How do I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$sql1 = $con->query("SELECT (status) FROM `seita`");
$i = $sql1->num_rows;
echo $i;
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$res = mysqli_fetch_row($sql);
}
?>
The answer given by Rohit Mittal gave me array to string conversion error. What do I do next?
You can fetch all in one query with fetch_all() of mysqli
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$result = $con->query("SELECT status FROM `seita`")->fetch_all();
You could try to do it all in one line. Maybe something similar to this:
$res = $con->query("SELECT status
FROM `seita`
WHERE RollNo between 1 and (
SELECT count(status)
FROM `seita`
)
")->fetch_all();
You want to append to an array search google php array append which gives array_push($stack, "apple", "raspberry");
// Declare arrray
$res = []
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
// Append result to array
array_push($res, mysqli_fetch_row($sql));
}
You need to make an array and need to get only status value as below:
$res = [];
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$statusData = mysqli_fetch_row($sql);
$res[] = $statusData['status'];
}

Create nested JSON objects using PHP

I have the following MySQL table:
id desc qty
--------------------
10 abc 5
20 xyz 12
30 qwe 9
How can I use PHP/MySQL query to create the following JSON file?
{
"10":{"desc":"abc","qty":"5"},
"20":{"desc":"xyz","qty":"12"},
"30":{"desc":"qwe","qty":"9"}
}
Here is my attempt
$query="SELECT id,desc,qty FROM table";
$result = #mysql_query($query);
while ($row=mysql_fetch_object($result))
{
$data[]=$row;
}
echo json_encode($data);
The result is an array and I am not sure how to display it correctly
[
{"id":"10","desc":"abc","qty":"5"},
{"id":"20","desc":"xyz","qty":"15"},
{"id":"30","desc":"qwe","qty":"9"}
]
Any help is appreciated
There are many ways to achieve this.One of them is below. changes your database credentials and table name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM TableName";
$result = $conn->query($sql);
$results_array =array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results_array[$row['id']] = array(
'desc'=>$row['desc'],
'qty'=>$row['qty'],
);
}
} else {
echo "0 results";
}
$json_array = json_encode($results_array);
echo $json_array;
Results should be look alike
{
"1":{"desc":"abc","qty":"12"},
"2":{"desc":"xyz","qty":"54"}
}
Thanks for editing your question. You can change the structure of your results with another loop:
foreach($data as $d)
$r[$d->id] = ['desc' => $d->desc, 'qty' => $d->qty];
$data = $r;
right above:
echo json_encode($data);
or you could adjust your while loop to get the same result:
$data[$row->id] = ['desc' => $row->desc, 'qty' => $row->qty];
or you could use array column (again right above json_encode):
$data = array_column($data, null, 'id');
The last example produces a slightly different output, but you can still use it in many situations. If you can't the first two options are preferable.

Is there any way to use the all fetched row's data from mysql database within a single dimentional php array function

This is the traditional way where I can fetch all rows with datas and run a while loop to get them one by one with mysqli_fetch_array() function.
$con = mysqli_connect(YOURLS_DB_HOST,YOURLS_DB_USER,YOURLS_DB_PASS);
mysqli_select_db($con,YOURLS_DB_NAME);
$users=mysqli_query($con,"SELECT * FROM users"));
while($user=mysqli_fetch_array($users))
{
$user['email']; $user['pass'];
}
Now the question is I have to insert all the rows with the respective datas into the bellow array. How is this possible. Rows will inserted one by one probably like the single line commented line. And non commented are actual data what I want.
$user_password = array(
'username2' => 'password2',
/* You can have one or more*/ 'login'=>'password',
// $user['email'] => $user['pass'],
)
I have done something and current state is
$con = mysqli_connect(YOURLS_DB_HOST,YOURLS_DB_USER,YOURLS_DB_PASS);
mysqli_select_db($con,YOURLS_DB_NAME);
$users=mysqli_fetch_assoc(mysqli_query($con,"SELECT email, pass FROM users"));
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass3[] = array(
$email => $pass,
'hguhfg'=> 'nhgudfhg',
);
}
$yourls_user_passwords = $user_pass3;
//print_r($user_pass4);
/*output Array ( [0] => Array ( [test#example.com] => test [hguhfg] => nhgudfhg ) [1] => Array ( [demo#example.com] => demo [hguhfg] => nhgudfhg ) ) but disired output is Array ( [test#example.com] => test [hguhfg] => nhgudfhg [demo#example.com] => demo); */
If you just want login and password :
$users = mysqli_query($con,"SELECT login, password FROM sughi_users"));
$user = array();
foreach ($users as $aUser) {
$user[$aUser['login']] = $aUser['password'];
}
After all of your suggestion i have done the program. Thank you everyone. Here us the perfect code.
$users = mysqli_query($con, "SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass3[] = array(
$email => $pass,
);
}
foreach($user_pass3 as $arr) {
foreach($arr as $key => $data) {
$user_pass[$key] = $data;
}
}
// print_r($user_pass);
$user_pass_final = $user_pass;
The [] notation on a variable makes it a dynamic array. So don't use array() after that. You can also pass a unique key inside the brackets if you prefer.
$users = mysqli_query($con, "SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass_final[$email] = $pass;
}
print_r($user_pass_final);
Additionally you are double fetching, and fetching on an array which should fail so instead of:
$users=mysqli_fetch_assoc(mysqli_query($con,"SELECT email, pass FROM users"));
while ($row = mysqli_fetch_assoc($users)) {
You should assign the query return to $users:
$users=mysqli_query($con,"SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
Final note, passwords should NOT be stored in plain text. See https://security.stackexchange.com/questions/120540/why-shouldnt-i-store-passwords-in-plaintext
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysqli_connect($servername, $username, $password, $database); if (!($conn))
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT email,pass FROM users";
$result = mysqli_query($conn, $sql);
$newArray = array();
if (mysqli_num_rows($result) > 0)
{
/* loop for return all the fetched data one by one */
while($row = mysqli_fetch_assoc($result))
{
/* store the data from mysqli array in variable use same code for for as much as type of data you want*/
$email=$row["email"];
$password=$row["pass"];
/* you can also add some value manually into the same array like this */
$newArray['admin']= 'adminpass';
$newArray['test']= 'testpass';
/* You have to build one array variable which includes 2 type of data 1st one as array index and 2nd one as value */
$newArray[$email]= $password;
}
}
else
{
echo "0 results";
}
$conn->close();
/* print the array or store in another variable to use elsewhere. */
print_r($newArray);
/* or print indiviual data one by one like data1, data2 */
echo "<br>";
foreach($newArray as $x => $x_value)
{
echo "Email=" . $x . ", Password=" . $x_value;
echo "<br>";
}
/* this example shows email and password in plain text just for the special requirement of the project. It's recomended to not to use passwords in plain text and inside the code. */
//Credits gose to https://www.facebook.com/ansarali.molla.9
?>

Loop mysqli_result

I can't seem to figure out how to loop through the rows in this object array. For example, how would I echo the value in each row?
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
When I print_r($result); I get
mysqli_result Object ( [current_field] => 0 [field_count] => 1
[lengths] => [num_rows] => 15 [type] => 0 )
Try to loop on $result with foreach loop:
<?php
foreach($result as $key => $val)
{
echo "key is=> ".$key." and Value is=>".$val;
}
Keys will be current_field field_count etc.
Make sure your are connected to the database. Example mysqli connection below.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "databasename";
$db = new mysqli($hostname, $username, $password, $database);
What you need is to fetch the data on your query and loop through on it. Like this
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
while ($manager_row = $result->fetch_assoc()) {
echo $manager_row ['my_ids'];
echo '<pre>'; print_r($manager_row);echo '</pre>';
}
You can also use fetch_all(). Like this
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
$all_results = $result->fetch_all();
foreach($all_resuls as $data){
print_r($data);
}
Are you looking for this?
while($row = mysqli_fetch_array($result)){
echo $row['my_ids'].'<br />';
}

Creating a php associative array that can be json encoded

Ok so I have a could similar to this.
<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = while($row = mysqli_fetch_assoc($grab)){
"id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
json.encode($cars);
So I know that the while loop is a bit strange, but I need to know how I adjust the code so I can json encode the resulting variable, so I get an array of associative arrays.
I know this code wont work but how do I get it to work, I'm guessing its going to take a little more work, but am very new to coding and php.
Any help would be appreciated, thanks.
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
$cars[] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
}
json_encode($cars);
this is correct syntax and method
Close?
$the_array = array();
while($row = mysqli_fetch_assoc($grab)) {
$temp = array();
$temp['id'] = $row['Id'];
$temp['name'] = $row['Name'];
$temp['color'] = $row['Color'];
$the_array[] = $temp;
}
json_encode($the_array);
mysql methods are depreciated in PHP, try to use PDO extension.
Use the following
$grab = mysql_query($con, "SELECT * FROM DB");
$cars = array(); $i = 0;
while($row = mysql_fetch_array($grab))
$cars[$i++] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
header('Content-Type: application/json');
json.encode($cars);

Categories