if else condition not validating for mysql query in php mysql - php

Hi i have a small problem with the execution of query using if else condition.
I have 2 tables i.e dashboard_widget and dashboard_widget_users and in both this table i store my unserialize configuration.Users will always get the configuration from dashboard_widget_users table.But if the configuration is Null then it will take bydefault configuration from dashboard_widget table.I just want to use if else condition and i tried to do so but unable to execute it properly.The condition for if(!empty($empty_config)) is getting satisfied but if it empty then i am not getting any result.Thank you.
dashboard_widget_users table
dashboard_widget table
Here is my php code:
$query = "SELECT dashboard_widget_users.configuration
FROM dashboard_widget_users
INNER JOIN yw_user ON dashboard_widget_users.dsnr_yw_user = yw_user.intern
INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.id
WHERE dashboard_widget_users.dsnr_yw_user =10 AND dashboard_widget.id =1 ";
$result = mysql_query($query, $myConnection);
if ($row = mysql_fetch_assoc($result))
{
$empty_config=$row['configuration'];
if (empty($empty_config)) {
$sql="SELECT dashboard_widget.configuration FROM dashboard_widget WHERE Id =1";
$sql_result = mysql_query($sql, $myConnection);
$results = mysql_fetch_assoc($sql_result);
$config= unserialize($results['configuration']);
}
if (!empty($empty_config)) {
$config = unserialize($row['configuration']);
foreach($config as $val)
{
//Here is my further things.....
}
}
}

You should check if there are any rows found, if so, display the information, if not, display the default info:
<?php
$query = "SELECT dashboard_widget_users.configuration
FROM dashboard_widget_users
INNER JOIN yw_user ON dashboard_widget_users.dsnr_yw_user = yw_user.intern
INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.id
WHERE dashboard_widget_users.dsnr_yw_user =10 AND dashboard_widget.id =1 ";
$result = mysql_query($query, $myConnection);
if( mysql_num_rows( $result ) > 0 ) {
// row found, display it
}
else {
// row not found, display default
}
?>
Note: you should look into mysqli_* functions, mysql_* functions are deprecated. Also check this link.

Related

MySQL - Join part of query to a new query?

I've got the following code which queries a table. Then it uses the result to make another query. That result is then used to make a third query.
But how do I grab the userid field from the 2nd query in order to grab a name from a users table and join that to the result of the 3rd query?
Please note once I figure out the code I will convert this to a prepared statement. It's just easier for me to work with legacy code when figuring out queries.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "SELECT opid, userid from audioposts WHERE audioid = $newaudio" ;
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$opid = $row[opid];
$opuserid = $row[userid];
$getreplies =
"SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
} "SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
}
echo json_encode($dbdata);
The result I need are rows of json encoded instances of $getreplyresults with the $row[userid] from the original result joined to each row.
Here's what I did in the end. Now I just have to figure out how to convert this to a prepared statement in order to avoid malicious injection.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'
";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}

PHP SQL INSERT INTO statement not working directly after table creation [duplicate]

<?php
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query4) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>
All the queries work independently but am really struggling putting all the pieces together in one single result so I can use it with mysql_fetch_array.
I've tried to create views as well as temporary tables but each time it either says table does not exist or return an empty fetch array loop...logic is there but syntax is messed up I think as it's the 1st time I had to deal with multiple queries I need to merge all together. Looking forward to some support. Many thanks.
Thanks to php.net I've come up with a solution : you have to use (mysqli_multi_query($link, $query)) to run multiple concatenated queries.
/* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");
$query = "SQL STATEMENTS;"; /* first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print your results */
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
EDIT - The solution above works if you really want to do one big query but it's also possible to execute as many queries as you wish and execute them separately.
$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());
$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());
while($row = mysqli_fetch_array($result2)) {
echo $row['c1'];
}
It seems you are not executing $query1 - $query3. You have just skipped to $query4 which won't work if the others have not been executed first.
Also
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
should probably be
$query4 = "SELECT *, #rank_change := prev_rank - current_rank as rank_change from final_output";
or else the value of rank_change will just be a boolean, true if #rank_change is equal to (prev_rank - current_rank), false if it is not. But do you need #rank_change at all? Will you use it in a subsequent query? Maybe you can remove it altogether.
Even better, you could just combine all the queries into one like this:
SELECT
curr.player,
curr.rank AS current_rank,
#rank_change := prev.rank - curr.rank AS rank_change
FROM
main_table AS curr
LEFT JOIN main_table AS prev
ON curr.player = prev.player
WHERE
curr.date = X
AND prev.date = date_sub('X', INTERVAL 1 MONTH)
You should concatenate them:
<?php
$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query .= " CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query .= " CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query .= " SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>

insert into database with condition

When I update the book_Status from table book to AVAILABLE I do not succeed to change reserve_Status to RESERVED. What's wrong with my script ?
reserve.php:
<?php
include 'dbconnect.php';
$query1 ="
SELECT b.book_Status, r.reserve_Status
FROM book b
JOIN reservations r
ON r.book_Accession = b.book_Accession
";
$result1 = mysql_query($query1) or die('SQL error');
$row1 = mysql_fetch_array($result1, MYSQL_ASSOC);
if ($row1['book_Status'] == 'Available')
{
$Reserved = "Reserved";
}
$query2 = "INSERT INTO reservations
WHERE reserve_Status = '$Reserved' ";
?>
You need a update query. and move that query into your if statement
if ($row1['book_Status'] == 'Available')
{
$Reserved = "Reserved";
$query2 = "UPDATE reservations SET reserve_status = 'reserved' WHERE book_Status='Available'";
}
The problem is that you changed the value of the variable $Reserved but you did not query the database to perform the update.

if(query1value = query2value) {} else {}

So, I am wondering how I can compare the result of one query to the result of another query in a if-statement. Like this:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
if($team==$lplayer){
//Do something
}
else{
//Do something else
}
This does not work... Why?
Now, why doesnt this work:
$tleague = mysql_query("SELECT teamId from team
WHERE leagueId=(SELECT leagueId FROM league WHERE leagueName='$leagueName')");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){}
else{}
You need to use mysql_fetch_assoc() on the query, and compare the returned values. Something like the below. What you're comparing is the two returned resource objects:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$t = mysql_fetch_assoc($team);
$p = mysql_fetch_assoc($tplayer);
if($t['teamId'] ==$p['teamId']){
//Do something
}
else{
//Do something else
}
However, you shouldn't be using mysql_* methods, instead look at using MySQLi // Tutorial.
You are not fetching any result from queries. Do something like
$team_result = mysql_fetch_array($team);
$tplayer_result = mysql_fetch_array($tplayer);
Then use fetched result to make your if condition
if($team_result['teamId'] == $tplayer_result['teamId'])
{
//do something
}
Also please stop using mysql as it is deprecated, switch to PDO or mysqli for new projects
Update
The new query have mistake. Why don't you use a join
$tleague = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` WHERE b.`leagueName` = '$leagueName'");
$tplayer = mysql_query("SELECT `teamId` FROM `player` WHERE `playerName`='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId'])
{
// do something
}
else
{
// do something else
}
UPDATED AGAIN
I merged all queries in one and i encapsuled data in the query '".$playerName."' and '".$leagueName."'
$query = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` LEFT JOIN `player` c ON b.`teamId` = c.`teamId` WHERE b.`leagueName` = '".$leagueName."' and c.`playerName`= '".$playerName."'");
if($row = mysql_fetch_array($query))
{
echo 'Found: ' . $row['teamId'];
}
else
{
echo 'Not Found.';
}
It does not work, because it's not the result of the query. You need to pass to a variable the mysql_result i.e.:
$result1 = mysql_result($team, 0);
$result2 = mysql_result($tplayer, 0);
if ($result == $result2) { ...
Try like this
$teamQuery = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$lplayerQuery = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$team = mysql_fetch_assoc($teamQuery);
$lplayer = mysql_fetch_assoc($lplayerQuery);
if($team['teamId']==$lplayer['teamId']){
//Do something
}
else{
//Do something else
}
do it like that
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($team);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){
//Do something
}
else{
//Do something else
}
EDIT:
on your second edit your problem is in the query itself .
try this one
$tleague = mysql_query("SELECT t.teamId from team inner join league l On t.leagueId = l.leagueId
WHERE t.leagueName='".$leagueName."' ");

How do I get PHP variables from this MySQL query?

I am working on an Asset Database problem using PHP / MySQL.
In this script I would like to search my assets by an asset id and have it return all related fields.
First I query the database asset table and find the asset's type. Then depending on the type I run 1 of 3 queries.
<?php
//make database connect
mysql_connect("localhost", "asset_db", "asset_db") or die(mysql_error());
mysql_select_db("asset_db") or die(mysql_error());
//get type of asset
$type = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
or die(mysql_error());
switch ($type){
case "Server":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,server.manufacturer
,server.model
,server.serial_number
,server.esc
,server.user
,server.prev_user
,server.warranty
FROM asset
LEFT JOIN server
ON server.id = asset.id
WHERE asset.id = 93120
");
break;
case "Laptop":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,laptop.manufacturer
,laptop.model
,laptop.serial_number
,laptop.esc
,laptop.user
,laptop.prev_user
,laptop.warranty
FROM asset
LEFT JOIN laptop
ON laptop.id = asset.id
WHERE asset.id = 93120
");
break;
case "Desktop":
//do some stuff that involves a mysql query
mysql_query("
SELECT asset.id
,asset.company
,asset.location
,asset.purchase_date
,asset.purchase_order
,asset.value
,asset.type
,asset.notes
,desktop.manufacturer
,desktop.model
,desktop.serial_number
,desktop.esc
,desktop.user
,desktop.prev_user
,desktop.warranty
FROM asset
LEFT JOIN desktop
ON desktop.id = asset.id
WHERE asset.id = 93120
");
break;
}
?>
So far I am able to get asset.type into $type. How would I go about getting the rest of the variables (laptop.model to $model, asset.notes to $notes and so on)?
Thank you.
$sql = "YOUR QUERY";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
echo 'Start Record<br />';
echo $row['type'].'<br />';
echo $row['company'].'<br />';
echo $row['location'].'<br />';
echo 'End Record<br /> <br />';
}
Try that out to see what you get then you can use data as you wish;
You may also want to look at mysql_fetch_array, mysql_fetch_row or mysql_fetch_object. Choose which best suits your needs.
What you're doing will not work:
$type = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
This puts a resultset into $type, not the type itself.
After you do that, you need to fetch a row, then fetch the field:
$result = mysql_query("
SELECT asset.type
From asset
WHERE asset.id = 93120
")
if($row = mysql_fetch_object($result)){
$type = $row->type;
// NOW you have the type in $type. Do something similar with the rest of the queries.
}
I guess you would want to do something like this:
$result = mysql_query($query);
$i = array();
while ($data = mysql_fetch_assoc($result)) {
$i[] = $data;
}
This would make $i a multidimensional array containing all of your query data and you could use it by doing the following
foreach ($i as $key => $value) {
echo $value['model'];
echo $value['serial'];
etc......
}
Please see:
http://us2.php.net/manual/en/mysql.examples-basic.php
http://us2.php.net/manual/en/function.mysql-query.php
You may take a look at http://php.net/manual/en/function.mysql-query.php.
A mysql_query returns a resource which contains the results of your query. This resource can be read out the following way:
$sql_result = mysql_query( [here your stuff] );
while ($row = mysql_fetch_assoc($sql_result)){
echo $row['model']; // prints the model
}
So, you have to loop through the result and traverse each row. row then is an associative array containing the single fields.
Hope this helps.
it must be just one table computers
so your code would be just:
<?php
//make database connect
mysql_connect("localhost", "asset_db", "asset_db") or die(mysql_error());
mysql_select_db("asset_db") or die(mysql_error());
$sql = "SELECT a.id, a.company, a.location, a.purchase_date, a.purchase_order,
a.value, a.type, a.notes, c.manufacturer, c.model,
c.serial_number, c.esc, c.user, c.prev_user, c.warranty
FROM asset a
LEFT JOIN computers c
ON c.id = a.id
WHERE a.id = 93120";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$data=array();
while($row = mysql_fetch_assoc($res)) $data[] = $row;
// now $data array contains all the rows returned
?>
Every time you see doubled code, y know you're doing something wrong.

Categories