I'm trying to build a 2d array in PHP with two loops using two different queries.
for some reason the page is not showing any message about any error that occurred.
It just reacts like the array doesn't exist.
Therefore I am assuming its because I did't handle the array right.
This is the code:
$stuarr= array(); ***//the 2d array initialization***
$query1 = "SELECT * FROM students WHERE userid= '$uid' ORDER BY name";
$stulist = mysqli_query($conn,$query1) or die ("cannot query the table1 " .mysqli_error($conn));
while ($students = mysqli_fetch_array($stulist)) {
${$students['name']}= array(); ******//the inside array initialization...the one that will insert to $stuarr***
$count=$_SESSION['counter'];
$sname=$students['name'];
$query3 = "SELECT * FROM ranks WHERE userid= '$uid' AND rankers='$sname' ORDER BY therate DESC";
$stur = mysqli_query($conn,$query3) or die ("cannot query the table1 " .mysqli_error($conn));
while ($sturank = mysqli_fetch_array($stur) && !$count==0) {
array_push(${$students['name']},$sturank['rated']);
$count=$count-1;
print_r(${$students['name']});
}
array_push($stuarr,${$stulist['name']});
print_r($stuarr); ***///this print is showing nothing***
}
I would love to hear your opinion about the code.
thank you!
Change
array_push($stuarr,${$stulist['name']});
into
array_push($stuarr,${$students['name']});
Related
I have two tables is sql 1) friends_details and 2) user_info.
Now using the below query am getting the list of friends of that particular using $number = is coming from app
$sql = "select friends from user_info WHERE user_number ='$number' ";;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
now $emparray have names of friends in String fromat. Now i want to pass this array into another query so that i can find the details of these friends. And Can't find the way to do. I have tried this code.
$friendsArray2 = "'" .implode("','", $emparray ) . "'";
$query120 = "SELECT * FROM friends_deataisl WHERE name IN ( $friendsArray2 )";
echo $query120;
and the result of echo $query120 is SELECT * FROM friends_deatails WHERE name IN ( 'Array','Array' )
So this means values are not going in the query. Any help would be appreciated.
And i have already checked $emparray is not empty it contains the name that means first query is right but the problem is in second query.
$emparray is a 2-dimensional array, not an array of strings, because $row in the first loop is an associative array.
You need to change the first loop to do:
$emparray[] = $row['friends'];
But you could just combine the two queries into a JOIN:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON fd.name = ui.friends
WHERE ui.user_number = '$number'
Also, the column name friends makes me suspect that this is a comma-separated list of names. Using = or IN won't work with that -- it will try to match the entire list with friend_details.name. It's best to normalize your database so you don't have lists in a column. If you can't fix that, you need to use FIND_IN_SET to join the tables:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON FIND_IN_SET(fd.name, ui.friends)
WHERE ui.user_number = '$number'
And in your original code, you'll need to explode $row['friends']:
$emparray = array_merge($emparray, explode(',', $row['friends']));
I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}
I'm trying to display a field from my MySQL database. It's in the table tblproducts in the row with the id is set to 1. And under the column qty.
This is the code I'm using:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database_name");
$available = "SELECT qty FROM tblproducts WHERE id = 1";
$result = mysql_query($available);
echo $result;
?>
However, I keep getting this message: Resource id #2
I've done a bit of research and seen where other people are having similar problems but most of them are trying to display their data in an HTML table whereas I just need the data from 'qty' to display. And of course I'm definitely not a MySQL guru.
Can anyone help me out with this please?
Try changing this:
$result = mysql_query($available);
To this:
$result = mysql_result(mysql_query($available), 0);
Let's start from the start. (I'll assume you have the connection set)
Form the query
$query = "SELECT `qty`
FROM `tblproducts`
WHERE `id` = 1";
Execute the query
$run = mysql_query($query);
Now, put the result in an assoc array
$r = mysql_fetch_array($run);
See the contents of the array
echo $r['qty'];
It's also advised that you move up from mysql to either mysqli, or PDO. PDO is preferred as you're not bound to the MySQL database model.
Try this:
Here you need to generate associative array and then get the resulting row.
$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";
$run = mysql_query($query);
$r = mysql_fetch_array($run);
echo $r['qty'];
-
Thanks
My page displays the name of players of a certain sports team using drop down menus. The coach can log in to pick his team and select the opposition which his team will play against.
When user has selected the team and opposition he clicks submit and the isset function is triggered.
Now I capture the values from the drop down menus and upload it to the correct table in the DB. Everything is pretty straight forward however when I click submit I get the error in the tittle. Any help would be appreciated
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
$opponents_id = $_REQUEST['players'];
var_dump($player_ids);
var_dump($opponents_id);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) )
{
$selected[] = $row['name'];
$position[] = $row['position'];
}
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$fixture_id[] = $row['fixture_id'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team` (`selection_id`, `fixture_id`, `player_position`,`player_name`)
VALUES ('$fixture_id[$i]','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo $fixture_id[$i];
echo'<br>';
}
The Unknown column 'Array' in 'where clause' error means literally what it says -- you tried to put an array value into your where clause.
In this line:
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
You are using the $opponents_id variable which your var_dump shows is an array containing five values. So, you need to use the IN clause and list them out (just like you did for $player_ids):
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` IN (" . implode(",", $opponents_id) . ");")
or die (mysql_error());
Note: Hopefully you are aware of the tiring subject of the mysql_* family of functions. These are being deprecated and are insecure. I wrote about it a while back: http://www.jorble.com/2012/06/you-are-vulnerable-for-sql-injection/
bodi0 is right, your $opponents_id is an array , if it must be an array so do some things like that
$opponents_id_text=implode(',',$opponents_id);
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` in ($opponents_id_text)")
or die (mysql_error());
The problem is in your second SQL query:
WHERE `fixture_id` = $opponents_id" -
Here the $opponents_id is array (it is converted automatically to array when you assign the value to it from the $_REQUEST, because the HTML component select sends the options as array).
Just implode() it also, like you did for $player_ids.
you did not specified Array properly in sql query.
when we use Arrays we have to specify array number in query
I have an array of player's IDs. There will generally be about 5 players, not likely to be more then a dozen:
$cplayers= array(1,2,5);
I want to display the players names as a list.
$query = "SELECT username,id FROM users ORDER BY id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$playercounter =0;
while ( $row = mysql_fetch_array($result) ) {
if ($row['id'] == $cplayers[$playercounter]) {
echo "<li>".$row['username']."</li>";
$playercounter++;
}
}
So I'm pretty sure this isn't the most efficient way I could do this. Would it be better to do individual queries?
Also is there a good way to exit the while loop once $cplayers is done?
just change your query to this:
$query = "SELECT username,id FROM users WHERE id IN (".implode(",",$cplayers).")ORDER BY id";
this will return the correct players you're looking for.
Based on how I'm interpreting this, I'd use the MySQL IN clause, e.g.
$id_list= array(1,2,5);
$sql= 'SELECT username FROM users WHERE id IN('. join(",",$id_list) .') ORDER BY id';
$result= mysql_query($sql) OR die(mysql_error());
while($row= mysql_fetch_assoc($result)) {
echo "<li>{$row['username']}</li>";
}
This targets only those id values in the list, is that what you want?
Well apparently the answer is rather to normalize my database, have a separate (third) table for the join of the two rather than using an array w/in the second table.