Values stored multiple times into array - php

I am trying to save values from my database into an array, this works however it shows some of the values multiple times some of them 2 and other ones 3 times.
<?php
$conn = mysqli_connect("127.0.0.1", "root", "", "testdb");
$sql = ("SELECT * FROM vraag");
$result = $conn->query($sql);
// run query
$query = mysqli_query($conn, $sql);
// set array
$array = array();
// look through query
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['vraag']; // etc
}
while ($row = mysqli_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo $columnData;
}
}
?>

Related

Select multiple rows from database

I want to be able to select all rows where a value matches with the one I'm calling for in php
This is what I have for now and the only thing I get is the first row. Not the other rows.
<?php>
session_start();
require "db.inc.php";
$id = $_SESSION['userId'];
$sql = "SELECT followingId FROM following WHERE followerId=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
echo var_dump($result);
$followedId = $result['followingId'];
echo $followedId;
And $conn is the connection variable in db.inc.php
You must iterate through the results array you are fetching
while ($row = mysqli_fetch_array($result)) {
foreach($row as $field => $value) {
//do something with $field and $val
}
}

How to display the database name in json

Am fetching values from mysql to json. All my data's are showing properly now i want to display database name inside json. any help can be appreciated.
json.php code :
<?php
$connect = mysqli_connect("localhost", "root", "", "recruiter");
$sql = "SELECT * FROM recruiter";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo (json_encode($json_array));
?>
Output:
{
"here i want db name":[
{
"job_id":"1",
"job_title":"Java developer",
"job_description":"Java description",
"job_details":"details",
"job_skills":"java",
"job_min_exp":"0 Yr",
"job_max_exp":"2 Yrs",
"company_name":"",
"job_location":"",
"industry":"",
"department":"",
"job_role":"",
"owner_name":"",
"owner_mobile":"",
"owner_email":"",
"owner_description":" "
}
]
}
As per your output, Understand is database name is array under the multidimensional array. To show database name inside the JSON.
Try this code
<?php
$database_name = "recruiter";
$connect = mysqli_connect("localhost", "root", "", $database_name);
$sql = "SELECT * FROM recruiter";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode(array($database_name => array($json_array)));
?>

MySQL Query Returns 0 When Running Multirowed Response Query

When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();

Collect all ID's MySQL

I've done this:
$result = mysql_query("SELECT image, id FROM store WHERE username = '$username_show'");
$num_rows = mysql_num_rows($result);
$ids = mysql_fetch_assoc($result);
$ids = $ids['id'];
for ($i = 0; $i < $num_rows; $i++) {
echo "<img src='get.php?id=$ids[$i]' height='300'><p/>";
}
I want to show all of my photos that has that username. But the $ids array only gets one index, and that's the last ID. What am I doing wrong?
Like #Matthew said thet are deprecated use :
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $result->fetch_assoc();
echo htmlentities($row['row']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['row']);
To answer your comment :
- use the array function
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$result = $mysqli->query("SELECT id FROM store WHERE username = '$username_show'");
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}

Returning Multiple Rows with MySqli and Arrays

For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?
You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();
Why not use directly like this:
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
I'm late, but I believe this is what you wanted to achieve:
$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
function display_posts () {
global $mysqli;
global $fields;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
$posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
if ($posts -> num_rows > 0) {
while ($row = $posts -> fetch_assoc()) {
$value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
}
}else {
echo 'No records found.';
}
}
//Call the function
display_posts ();

Categories