mysql query select multiple rows where column value is same - php

i have this table
Column_1 Column_2
1 value1
2 value1
3 value2
My php query is
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
print_r($query);
This returns only the 1st row. I am looking to display row 1 and 2. When I run the SQL in phpmyadmin it returns row 1 and 2. However, the php script only returns row 1... I also did an
echo count($query);
But it returns only 1. What am i doing wrong?

$query = "SELECT * FROM `table` WHERE `Column_2` = 'value1' ";
$res = mysql_query($query);
if(mysql_num_rows($res)!=0) {
while($rowData = mysql_fetch_array($res)) {
var_dump($rowData);
}
}
Use mysql_num_rows to count number of results.
Use mysql_fetch_array or mysql_fetch_assoc to fetch data.

$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_assoc())
print_r($row);
You need add fetch in cycle.

Use mysql_fetch_array() function
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_array($res))
{
echo $row['Column_1'];
echo $row['value_1'];
}

Related

get required result in sql

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

How to get result from query and insert the results in other table?

I did query to the database where I need the results from it and then store it in a variable. Then I will pass the variable to the INSERT INTO statement but for some reason my code does not work. This is my code/
$query = "SELECT * from animals where old= 1 AND user_id=".$_SESSION['user_id'];
$result = mysqli_query(mysqli_connect("","","", ""), $query);
while ($row = mysqli_fetch_array($result))
{
$variable[] = $row['number'];
}
//now I will pass the $variable to the INSERT INTO statement
if(isset($_POST['submit_d']))
{
foreach($variable as $var)
{
$query="INSERT INTO selectedanimals(number) VALUES ({$var},2)";
mysqli_query($con, $query) or die (mysql_error());
}
?>
<script>
alert("Animal added.");
self.location="chooseAnimals.php";
</script>
<?php
}
?>
You can use INSERT INTO ... SELECT for this purpose in a single query:
INSERT INTO selectedanimals (number)
SELECT number
FROM animals
WHERE old = 1 AND user_id = some_id
PHP code:
$query = "INSERT INTO selectedanimals (number) ";
$query.= "SELECT number FROM animals WHERE old = 1 AND user_id = ".$_SESSION['user_id'];
mysqli_query($con, $query) or die (mysql_error());

Getting exact value from fetched array from MySql

Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";

Update rows of a SQL table

I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>

Why isn't my PHP working when I try to count the number of rows in a table?

Why isnt this working?
mysql_select_db('a2943462_Pages');
$num_rows = mysql_query("SELECT COUNT(*) FROM PagesInfo");
echo $num_rows;
mysql_query("INSERT INTO `a2943462_Pages`.`PagesInfo`(`ID`, `Title`, `Video`, `Posted`) VALUES ('".$num_rows."', '".$Title."', '".$Embed."', '".$name."')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Because it now echoes:
Resource id #9
but i tought it would echo 4 instead because i have 3 rows inside the Table
Change this:
$num_rows = mysql_query("SELECT COUNT(*) FROM PagesInfo");
To this:
$num_rows = mysql_result(mysql_query("SELECT COUNT(*) FROM PagesInfo"), 0);
This is the PHP method:
$sql="SELECT * FROM pages_info";
$result = mysql_query($sql, $con) or die (echo "$sql" );
$rows = mysql_num_rows($result);
you should do two queries:
first query what you want to show:
SELECT SQL_CALC_FOUND_ROWS * FROM PagesInfo
and second query to get number rows returned:
SELECT FOUND_ROWS()
The in your insert the number of rows returned
The query in php is
$rows = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM PagesInfo");
$rs = mysql_query("SELECT FOUND_ROWS()");
$r = mysql_fetch_row($rs);
mysql_free_result($rs);
$row_num = $r[0];

Categories