Array value not working - php

/*mysql table admin
id=1, user_name = mike
id=2, user_name = sam*/
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = array();
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = array('user' => $row['user_name']);
}
foreach($user_name_array as $key => $record){
$record_values .= "{$record['user']},";
}
$record_values = substr($record_values, 0, -1);
// $record_values is: mike,sam
$userThatHaveThePermission = array($record_values);
if (in_array(mike, $userThatHaveThePermission)){
echo "do something"
}
my question is about the values of variable $record_values this variable not working in: $userThatHaveThePermission = array($record_values);
If I add the user names(mike,sam) to $userThatHaveThePermission = array(mike,sam); everything working fine, WHY? did I miss something.

I think you are beginner in php-mysql. I would refactor your code for you.
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = [];
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = $row['user_name'];
}
$userThatHaveThePermission = $user_name_array;
if (in_array('mike', $userThatHaveThePermission)){
echo "do something";
}
But take advice of the people commenting on your status. Do not use mysql_query. Use some framework.

Related

PHP JSON generation problems

The code below should send back an json with informations in a Database.
It takes two parameters grade and subject. The problem ist, when I use parameters are not in the database behind everything works as expected no entry, but if it would get an answer from the database nothing appears. I mean really nothing. The values i need are there i tried this and no errors are logged into the logging file. As server runs apache2 with php5.6.22 on Debian. I don't know what i did wrong. Hopefully someone can help me.
The Code:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".$subject." AND grade=".$grade;
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die();
}
$response = array();
$response['books'] = array();
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row ["fullname"];
$book['ISBN'] = $row ["ISBN"];
$book['id'] = $row ["id"];
array_push($response['books'], $book);
}
$response['response'] = "1";
print(json_encode($response));
die();
I think this might be your problem:
array_push($response['books'], $book);
as far as I know you can't push a variable into a specific index of an array since no key is provided for the item being pushed.
It would be better to do this as follows:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".mysqli_real_escape_string((htmlspecialchars_decode($subject, ENT_QUOTES)))." AND grade=".mysqli_real_escape_string((htmlspecialchars_decode($grade, ENT_QUOTES)));
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die('sql failed');
}
$response = array();
$response['books'] = array();
$response['validator'] = 'valid';
$i = 0;
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row["fullname"];
$book['ISBN'] = $row["ISBN"];
$book['id'] = $row["id"];
$response['books'][$i] = $book;
$i++;
}
$response['response'] = "1";
var_dump($response);
//echo json_encode($response);
die();

Insert results of multiple tables into one json_encode()

Excuse my language mistakes, I speak French.
I did some research on this site and elsewhere, but what I have found didn't solve my problem.
I am doing a site where people can post their stories. I'm working on a page where the author should be able to see his stories and chapters of each of them.
I do a query on two tables to get the titles of stories and chapters. I have a table "stories" in which there is the title and summary of each story (and other stuff like id and date of publication). And another table called "chapters", in which there is the title of each chapter and the id of the story to which they belong.
I would like to retrieve these items later in my html, to have something like this:
Story title 1
Chapter 1
Chapter 2
So I do a json_encode () but JSONLint said that the json I get is invalid. PHP is new to me, I began to learn so I'm probably not writing my code correctly.
Here is my code:
<?php
session_start();
require_once('connexion_db.php');
if($db=connect()){
$userID = $_SESSION['id'];
$arr = array();
$reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
$resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
foreach ($resChapitres as $c){
$chapTitre = $c['titre_chapitre'];
}
$arr = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}
}else{
echo "bdd non connectée.";
}
?>
I tested the method proposed here, but the result is worse.
I don't know what to do :(
Thanks for your help!
It seems like you'd want the inner loop to go more like this:
$chapTitre = array();
foreach ($resChapitres as $c){
$chapTitre[] = $c['titre_chapitre'];
}
So your resulting JSON would include all the chapter titles.
Also, as it stands, you're listing a series of unconnected JSON objects, which should probably be a single array to be a legal JSON object.
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
$chapTitre = array();
foreach ($resChapitres as $c){
$chapTitre[] = $c['titre_chapitre'];
}
$arr[] = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
Will collect them all and output as a list.
[
{
'titre': 'Title 1',
'chaptitre': ['Chapter 1', 'Chapter 2']
},
{
'titre': 'Title 2',
'chaptitre': ['Chapter 1', 'Chapter 2', 'Chapter 3']
},
]
<?php
session_start();
require_once('connexion_db.php');
if($db=connect()){
$userID = $_SESSION['id'];
$arr = array();
$reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
$resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);
$chapTitres = array();
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
foreach ($resChapitres as $c){
$chapTitres[] = $c['titre_chapitre'];
}
$arr[] = array('titre' => $recitTitre, 'chaptitres' => $chapTitres);
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}else{
echo "bdd non connectée.";
}
?>
> For Me this is Worked !
<?php
header('content-type: application/json');
date_default_timezone_set('Asia/Dhaka');
$DatabaseName = "";
$HostPass = "";
$HostUser = "";
$HostName = "LocalHost";
$db_connect = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$userid = $_GET['id'];
$status = $_GET['status'];
$rows = array();
$datas = array();
$result = mysqli_query($db_connect, "SELECT id FROM drivers WHERE phone = '$userid'");
if ($result)
{
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$result = mysqli_query($db_connect, "SELECT `delivery_id` , `date`, `time` FROM `driver_orders` WHERE driver_id='$id' AND `status` ='$status'");
mysqli_set_charset($db_connect,"utf8");
while ($row = mysqli_fetch_assoc($result))
{
$d_id = $row['delivery_id'];
$data = mysqli_query($db_connect, "SELECT r_name,r_number,r_zone,r_address,amount FROM deliveries WHERE id = '$d_id'");
while ($row2 = mysqli_fetch_assoc($data))
{
$datas[] = array(
"r_name" => $row2['r_name'],
"delivery_id" => $row['delivery_id'],
"time"=> $row['time'],
"date"=> $row['date'],
"r_number" => $row2['r_number'],
"r_zone" => $row2['r_zone'],
"amount" => $row2['amount'],
"r_address" => $row2['r_address']
);
}
}
}
echo json_encode($datas);
?>

Why is the query returning only one set of data?

The problem I have is when I echo or print the following variables, the data I receive is that of the last business listed in my table only.
At present no matter the listing I click I get the same set of data for the last business returned.
As you can see in the below code I am passing the business_name from the clicked listing to be used in my query to find the relevant business profile information.
$business_name = mysql_real_escape_string($_GET['business_name']);
$query = "SELECT
business_id,
category,
years_recommended,
profile_size,
business_name,
established,
employees,
service,
strengths,
ideal_for,
reassurance
FROM
business_data
WHERE
business_name = '$business_name'
AND
profile_size = 'A'
OR
profile_size = 'B'
OR
profile_size = 'C'
OR
profile_size = 'D'
OR
profile_size = 'E'";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
}
echo...
If you need more information please let me know.
Is there anything wrong with my code?
Many thanks in advance.
Your echo call is outside the fetch loop, so you'll only see the last result even though the others were returned.
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
// Echo **inside** the loop
echo...
}
If you wish, you can store all the results in a large array, which can then be used anywhere subsequently in your script, as many times as needed:
// Array for all results
$results = array();
while($row = mysql_fetch_array($result)) {
// Append each row fetched onto the big array
$results[] = $row;
}
// Now use it as needed:
foreach ($results as $r) {
echo $r['profile_size'];
print_r($r);
}
your echo should be inside the loop

How do I add data from two tables in mySQL and PHP?

I have a table with two fields, named credithour and gradepoint.
I want to add the data from each row of credithour with gradepoint.
My code :
$totalcredithour = 0;
$GPA = "SELECT * FROM $dept_stu_id WHERE sessionyear = '$sessionyear'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = "$data[credithour]";
$gradepoint = "$data[gradepoint]";
echo $totalcredithour += $credithour;
}
What am I doing wrong?
It added data, but showing the first credit hour also besides result.
Suppose, here i entered two data 3 and 5. When I run this code it echo 38. Which means "3+5=8" and 1st credithour = "3".
Actually other answer are wrong, you're doing or die(mysql_error()); next to a string, that's not right.
Your code should be like this..
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = `".$sessionyear."` ";
$resultGPA = mysql_query($GPA) or die(mysql_error());
while($data = mysql_fetch_array($resultGPA, MYSQL_ASSOC))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += $credithour; //Make sure `$totalcredithot` isn't null/doesn't exist.
}
try something like this in your while loop:
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
Try it like this
I have edited the answer and added the floatval function
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = '".$sessionyear."'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += floatval($credithour);
}

Need Help With Implementing Simple Stuff with PHP and MYSQL

Here is my code -
<?php
$u = $_SESSION['username'];
while($fetchy = mysqli_fetch_array($allusers))
{
mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
$result= mysqli_fetch_array($query);
$email = mysqli_real_escape_string($connect,trim($result['onuser']));
echo $email;
if($email){
mysqli_select_db($connect,"users");
$select_name = "select name, icon from profile where email = '$email'";
$query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
$results= mysqli_fetch_array($query_2);
$name = mysqli_real_escape_string($connect,trim($results['name']));
$icon = mysqli_real_escape_string($connect,trim($results['icon']));
echo $name;
}
}
NOw, there are two reponses in db. So, two names are getting echoed, but they both are SAME. Why so? Eg
DB - NAMEs - Apple and Orange.
Displayed - Apple Apple.
Database example -
SESSIONUSERNAME OnUSer
s#s.com apple
s#s.com orange
EDITED
Using #endophage's method -
AppleOrange and AppleOrange.
As your loop stands now, $u will always be the same, so $select will always have the same value, and so will $email, and so will $select_name, so it is no surprise that the same record keeps coming back.
Edit
If the $select_name query returns multiple results, then you need to loop through the results with a while loop like the other queries.
Try this, you had your while loop in the wrong place:
<?php
$u = $_SESSION['username'];
mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
while($result = mysqli_fetch_array($query))
{
$email = mysqli_real_escape_string($connect,trim($result['onuser']));
echo $email;
if($email){
mysqli_select_db($connect,"users");
$select_name = "select name, icon from profile where email = '$email'";
$query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
$results= mysqli_fetch_array($query_2);
$name = mysqli_real_escape_string($connect,trim($results['name']));
$icon = mysqli_real_escape_string($connect,trim($results['icon']));
echo $name;
}
}

Categories