I would like to ask how can I display many rows of data instead of only one row. The following code will only display one row of record instead of multiple records are available. I'm using mysqli_prepare statements here. Or the problem is on my android studio coding? My application is implemented with login function and coding as below.
<?php
$host="DB_HOST";
$user="DB_USER";
$password="DB_PASSWORD";
$db="DB_NAME";
$con = mysqli_connect($host,$user,$password,$db);
$parentic=$_POST["ParentIC"];
$password=$_POST["Password"];
$selectquery = mysqli_prepare($con, "SELECT Parents_Data.Name, Student_List.StudName, Student_List.StudIC, Student_List.Form,Student_List.Class,discipline_record.Date,discipline_record.RulesCode, discipline_record.TypesofMistakes,discipline_record.Punishment FROM discipline_record LEFT JOIN Student_List ON discipline_record.StudIC = Student_List.StudIC LEFT JOIN Parents_Data ON Student_List.ParentIC = Parents_Data.ParentIC WHERE Parents_Data.ParentIC = ? AND Parents_Data.Password = ? ");
mysqli_stmt_bind_param ($selectquery, "ss", $parentic, $password);
mysqli_stmt_execute($selectquery);
mysqli_stmt_store_result($selectquery);
mysqli_stmt_bind_result($selectquery,$name,$studname,$studic,$form,$classs,$ddate,$code,$mistakes,$punishment);
$user = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
}
echo json_encode($user);
mysqli_stmt_close($selectquery);
mysqli_close($con);
?>
I would go with something like that:
$userGroup = array();
$user = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
array_push($userGroup,$user);
}
echo json_encode($userGroup);
It might be easier to use 2-dimensional array
$users = array();
while(mysqli_stmt_fetch($selectquery))
{
$users[] = array();
$users[][name]=$name;
$users[][studname]=$studname;
$users[][studic] = $studic;
$users[][form]=$form;
$users[][classs]=$classs;
$users[][ddate]=$ddate;
$users[][code]=$code;
$users[][mistakes]=$mistakes;
$users[][punishment]=$punishment;
}
foreach ( $users as $user )
echo json_encode($user);
It looks like you are doing correct query, but when fetching results using one flat array instead two dimension.
Also, try to avoid publishing your DB credentials in public :) It is quite dangerous.
So you should do something like that:
<?php
$host="YOUR_DB_HOST";
$user="YOUR_DB_USER";
$password="YOUR_DB_USER_PASSWORD";
$db="YOUR_DB_NAME";
$con = mysqli_connect($host,$user,$password,$db);
$parentic=$_POST["ParentIC"];
$password=$_POST["Password"];
$selectquery = mysqli_prepare($con, "SELECT Parents_Data.Name, Student_List.StudName, Student_List.StudIC, Student_List.Form,Student_List.Class,discipline_record.Date,discipline_record.RulesCode, discipline_record.TypesofMistakes,discipline_record.Punishment FROM discipline_record LEFT JOIN Student_List ON discipline_record.StudIC = Student_List.StudIC LEFT JOIN Parents_Data ON Student_List.ParentIC = Parents_Data.ParentIC WHERE Parents_Data.ParentIC = ? AND Parents_Data.Password = ? ");
mysqli_stmt_bind_param ($selectquery, "ss", $parentic, $password);
mysqli_stmt_execute($selectquery);
mysqli_stmt_store_result($selectquery);
mysqli_stmt_bind_result($selectquery,$name,$studname,$studic,$form,$classs,$ddate,$code,$mistakes,$punishment);
$user = array();
$users = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
$users[] = $user;
}
mysqli_stmt_close($selectquery);
mysqli_close($con);
echo json_encode($users);
Related
When I enter category name manually, I'm able to get its product but when I insert a variable to like the code, I get success but data is empty.
Connection file:
<?php
//cnnection.php
$server = "localhost";
$user = "root";
$password = "";
$db = "db_ecommerce_shoes";
$connect = new mysqli($server,$user,$password,$db);
Main script:
<?php
include '../connection.php';
With this, request is successful but data is empty
$name= 'name';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
With this, request is successful, data is loaded successful
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='Ladies Shoe'
";
$result = $connect->query($sql);
if($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode(array(
"success"=>true,
"data"=> $data,
));
} else {
echo json_encode(array(
"success"=>false,
));
}
Any other way of doing this will be much appreciated.
Any other way of doing this will be much appreciated
You should never be directly concatenating variables into the SQL query making it vulnerable to SQL injections. That is a major security issue.
Read about a simple and easy to understand version of prepared statements here.
In your case, try this out
$category = "Ladies Shoe"
$statement = $connect->prepare("SELECT * FROM tb_shoes WHERE catName = ? ")
$statement ->bind_param("s", $category);
$statement ->execute();
$result = $statement ->get_result();
Then you can loop through the results as above. Check if it works!
Try to assign
$name = 'Ladies Shoe';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
Does this work?
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.
I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.
$username = $this->session->userdata('username');
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"');
$rq = mysql_fetch_assoc($uidq);
$user_id = $rq['user_id'];
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user
And I don't know what to use next... I want to have something like:
foreach($favsr['bookmarked_song_id'] as $song_id) {
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_assoc($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.
It should be this:
$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
$songid = $row['bookmarked_song_id'];
...
}
mysql_fetch_array only loads one row,
it should be like that
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
while $favsr = mysql_fetch_array($getfavq);
{$songid=$favsr['bookmarked_song_id'];
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_array($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:
$username = $this->session->userdata('username');
//Select your user
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->limit(1);
$user_query = $this->db->get('users');
if($user_query->num_rows() > 0)
{
// We found a user
$user = $user_query->row(); // select a single row
// Grab this user's favorites
$this->db->where('user_id', $user->id);
$favorites_query = $this->db->get('favorites');
$songs = $favorites_query->result();
if($songs)
{
foreach($songs as $song)
{
$song_id = $song->bookmarked_song_id;
$tag = $song->bookmark_tag;
// Do stuff with data.
}
}
else
{
// No songs/favorites found, catch error
}
}
else
{
// No such user found, catch error
}
Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.
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;
}
}