Collect all ID's MySQL - php

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;
}

Related

JSON encoding not working

Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;

PHP Fusing two arrays

How to connect 2 arrays? I want that $new[$code]=$color, how can I do this? Below is my code:
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$code[] = $row['user_id'];
$color[] = $row['user_color'];
}
Declare the variable outside the while loop
$new = array();
Then inside while loop
$new[$row['user_id']] = $row['user_color'];
In the while loop...
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$new[$row['user_id']] = $row['user_color'];
}
If you need the arrays seperate for some reason you can do it later using array_combine, http://php.net/manual/en/function.array-combine.php.
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$code[] = $row['user_id'];
$color[] = $row['user_color'];
}
...
$new = array_combine($code, $color);

MySQL skipping first row

I have seen other people with that problem but the solutions I've seen aren't helping me, or I don't know how to use them :P
<?php
$ordre = "nom";
$croissance = "ASC";
if(isset($_GET["ordre"])){
$ordre = $_GET["ordre"];
};
if(isset($_GET["croissance"])){
$croissance = $_GET["croissance"];
};
$con = mysql_connect('localhost','root','');
mysql_select_db('sdj_jeux', $con);
$sql = "SELECT * FROM jeux ORDER BY $ordre $croissance";
$result = mysql_query($sql, $con);
$row = mysql_fetch_array($result);
$couleurcompteur = 0;
while ($row = mysql_fetch_array($result)){
$couleurcompteur += 1;
if($couleurcompteur % 2){
$classe = "pale";
} else {
$classe = "fonce";
};
?>
My code is skipping the first row of my database and I don't understand why.
Remove the line:
$row = mysql_fetch_array($result);
The while loop will grab the first row on the first iteration.
Resulting code:
<?php
$ordre = "nom";
$croissance = "ASC";
if(isset($_GET["ordre"])){
$ordre = $_GET["ordre"];
};
if(isset($_GET["croissance"])){
$croissance = $_GET["croissance"];
};
$con = mysql_connect('localhost','root','');
mysql_select_db('sdj_jeux', $con);
$sql = "SELECT * FROM jeux ORDER BY $ordre $croissance";
$result = mysql_query($sql, $con);
$couleurcompteur = 0;
while ($row = mysql_fetch_array($result)){
$couleurcompteur += 1;
if($couleurcompteur % 2){
$classe = "pale";
} else {
$classe = "fonce";
};
?>
Right here is your problem:
$row = mysql_fetch_array($result);
$couleurcompteur = 0;
while ($row = mysql_fetch_array($result)){
You call mysql_fetch_array() once before the while. This throws out the first row since you don't use it. Remove that un-needed call.
NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead

mysql PDO doesnt work

I've a little problem here..
I am using jquery easy UI to get data from mysql and then write a table in my php application..
nah.. the problem is.. my code or my query doesn't work..
When I am using my old mysql_connect, my code works well... but when I try to write it to mysql, I get nothing...
Here is my old code:
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;
$result = array();
$conn = mysql_connect('127.0.0.1','root','');
mysql_select_db('colosus',$conn);
$rs = mysql_query("select count(*) from user");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$rs = mysql_query("select * from user limit $offset,$rows");
$rows = array();
while($row = mysql_fetch_object($rs)){
array_push($rows, $row);
}
$result["rows"] = $rows;
echo json_encode($result);
and its the PDO query code...
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;
$result = array();
$rs = $db->query("select count(*) from user");
$row = $rs->fetch(PDO::FETCH_NUM);
$result["total"] = $row[0];
$rs = $db->query("select * from user as u, leveluser as l where u.idLevelUser = l.idLevelUser limit $offset,$rows");
$rows = array();
while($row = $rs->fetch(PDO::FETCH_OBJ)){
array_push($rows, $row);
}
$result["rows"] = $rows;
echo json_encode($result);
The last query (PDO) doesn't work.. I dont know why.. anybody can help me???
Looks like you forget to instanciate your $db object.
Try to put this before $result = array();
$db = new PDO("mysql:host=127.0.0.1;dbname=colosus", 'root', '');
create the pdo connection like
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
try query like
$query= $db->prepare("select * from user as u,
leveluser as l
where u.idLevelUser = l.idLevelUser
limit $offset,$rows");
$query->execute();
$result=$articlequery->fetch(pdo::FETCH_ASSOC);

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