Updating JSON Array in PHP - php

The following code is used to get all information and fetch it into a json array. Now I changed the 'author' to userids instead of username strings and I want to get the username strings from another table called 'login'.
But how can I get all 'author'-ids, queue another table and get all usernames with this id and update these in the fetched json array so I echo the usernames with the 'author'- id? I am not really used to JSON arrays, although this code always worked for me until I changed my database structure.
I tried researching some information but I did not find what I was looking for. Please excuse my bad english.
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "SELECT title, content, author, id, date, timestamp, importance, version FROM news ORDER BY timestamp DESC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(array("result"=>$result));
echo json_encode(array("result"=>$result));
mysqli_close($con);

You can change your SQL query to a join of 'news' and your 'author' table. Take a look at https://www.w3schools.com/sql/sql_join.asp there is an example for joining two table by customer id

Related

get data from two tables and collect them in array and count rows of one table result

I had two tables named fixture_list and OneRecord where fixture_list has 3 columns named Team1, Team2, player whereas OneRecord has columns like Team1, Team2, id, status so here I want to select all the data of fixture_list and put them into array whereas I want to count the number of rows based on this where condition fixture_list.Team1=OneRecord.Team1 and
fixture_list.Team2=OneRecord.Team2 from OneRecord, actually I am not able to distinguish between selecting the data and putting it into the array and counting the number of rows because I just want to count the rows of one record only. I know things like joins and mysqli_multi_query() can be performed but do not know how...I want to perform this thing in single query please help.
<?php
require_once('connect.php');
$sql = "select * from fixture_list";
if($res = mysqli_query($con,$sql)){
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('players'=>$row[3],
'team1_name'=>$row[1],
'team2_name'=>$row[2]
));
}
mysqli_free_result($res);
}
echo json_encode (array("list"=>$result));
mysqli_close($con);
?>
You can use a sub_query to do this. I don't understand your question perfectly (try using capitals and punctuation marks), but this should be probably the format to use.
$sql = "SELECT `fixture_list`.`team1_name`,
`fixture_list`.`team2_name`,
(
SELECT count(`OneRecord`.`Team1`) as `total`
FROM `OneRecord`
WHERE `OneRecord`.`Team1` = `fixture_list`.`Team1`
AND `OneRecord`.`Team2` = `fixture_list`.`Team2`
) as `Total_Players`
FROM `fixture_list`
GROU BY `fixture_list`.`id`";
$result = array(); // keep this outside the while loop to ensure the array is made
if($res = mysqli_query($con,$sql)){
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$result[] = $row;
}
}
This would give you a $result array as follows:
array(
'team1_name' => 'TEAMNAME1',
'team2_name' => 'TEAMNAME2',
'Total_Players' => INTEGER_VALUE
)
The INTEGER_VALUE is the number of rows from the subquery. You can edit the WHERE part of the subquery to your liking
Then you can do this to create a json object:
echo json_encode($result);
This will echo it, which is ideal if you use it with an Ajax function for example.

PHP/MYSQLi SQL SELECT on multiple table and return the result as json object

I am building user status app where other can comment. I fetch the json result through ajax and then display it in my ap. however my problem is when i run the query it return only one run for each replies even though there are multiple replies for each status. Honestly i dont know whether the problem is from the PHP loop or it is from the SQL queries it self. I have battling with this since two days now and have search other Stackoverflow question for help but still. I will be glad if anyone can help me. Thank you.
User status are saved in the Status table and all replies on each status is saved in the replies table.
These are my tables
Users Table = gcm_users
id
name
date
Status Table = gcm_status
id
userID
status
Replies Table = gcm_status_replies
id
statusID
userID
replies
This is my sql statement
$sqlSelect = ( 'SELECT gcm_status.status,
gcm_status.id,
gcm_status.userID,
gcm_status_replies.id,
gcm_status_replies.statusID,
gcm_status_replies.userID,
gcm_status_replies.message,
gcm_users.id,
gcm_users.name
FROM gcm_users INNER JOIN gcm_status
ON gcm_users.id = gcm_status.userID
INNER JOIN gcm_status_replies
ON gcm_status.id = gcm_status.id'
array(''), $conn);
PHP Loops is
foreach ($sqlSelect as $row) {
$respohnds = json_encode($row);
echo $respohnds;
}
I really need to help.
You're generating a separate json object for each row, and returning them one by one.
Maybe you should do this instead to return a single json object encoding your whole result set as an array.
$respondhs = array();
foreach ($sqlSelect as $row) {
$respohnds[] = json_encode($row);
}
echo $respohnds;

MYSQL Statement with Array Variable

So I have the following mysql statement saving to an array:
$sql = "SELECT did FROM did WHERE id = '$did_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_row()){
$did[] = $row;
}
That part works great. But now I need to take the values in the $did array and perform another lookup using the values in it. The way it works is we have users assigned to certain did's. So I find the did's that the user is assigned to (the $did array) and only show them results from another table based on those did values. I have no idea how this part works, but this is what my next statement needs to do:
SELECT * FROM log WHERE did_id = "the values in $did array"
Hope someone can help. I really appreciate it. I haven't really been able to find anything on it.
You can use php's join with mysql's IN to make comma separated strings you can also use implode , join() is an alias of implode();
SELECT * FROM log WHERE did_id IN( ".join(',',$did).")
One thing to mention here that your $did should contains ids in manner like
array("1","2","3"....)
So in your loop fetch first index that holds did column value
$did[] = $row[0];
Note: i assume did , did_id type is int or bigint

Show data from a specific row in MySQL

I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories