So I want to be able to use a WHERE command in SQL to select certain values from a table. This is my current code however it doesn't work
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if($_REQUEST=['MobileNumber']) {
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
} elseif($_REQUEST=['TeamGroup']) {
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
} else {
$Item = "SELECT a,b,c,d FROM Item";
};
$result = mysql_query($Item) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table>';
} else {
echo "No Items Assigned";
};
It works for when the url is test.php?MobileNumber=... but not when its has TeamGroup or nothing in the url. The url I have is like this: test.php?TeamGroup=11
EDIT: Added more code to let you see what I am trying to display
if($_REQUEST=['MobileNumber']){ its a wrong syntax
Try this
add this line in your url ?MobileNumber=Put your mobile num here. Thanks
than for Team group again this ?TeamGroup=put team group here.
if($_GET['MobileNumber']==TRUE){
$MobileNumber=$_GET['MobileNumber'];
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
}
elseif($_GET['TeamGroup']==TRUE){
$TeamGroup=$_GET['TeamGroup'];
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
This statement:
if($_REQUEST=['MobileNumber'])
will always be true, because you're assigning the ['MobileNumber'] array to the $_REQUEST global.
If you're trying to check whether the values are set in the $_REQUEST global, do the following:
if( isset($_REQUEST['MobileNumber']))
If you want to compare something using if condition then it must be like this
if(something == true){
// then do something
}
else{
//do something
}
Check the manual for more
What you are trying to do is not a valid one in php.You need to change this
if($_REQUEST=['MobileNumber']){
I think you can try like this
if(isset($_GET['MobileNumber']) && trim($_GET['MobileNumber'])){
And
elseif(isset($_GET['TeamGroup']) && trim($_GET['TeamGroup'])){
this should work...
if(isset($_GET['MobileNumber'])) //can also use if(isset($_GET['MobileNumber']) && !empty($_GET['MobileNumber']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = ".$MobileNumber;
}
elseif(isset($_GET['TeamGroup']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = ".$TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
You could try this:
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if(isset($_GET["MobileNumber"])) {
//If you enclose fields/table in `` and values in '' you won't run into quoting issues
//It's OK to not quote numbers, but you can quote them to stay standard
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `MobileNumber` = '$MobileNumber'";
};
if(isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `TeamGroup` = '$TeamGroup'";
};
if(!isset($_GET["MobileNumber"]) && !isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item`";
};
//Switch to mysqli_*
$result = mysqli_query($dbLink, $Item) or die ("Error in query: $Item. " . mysqli_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
};
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
};
print '</tr>';
$row = mysqli_fetch_assoc($result);
};
print '</table>';
} else {
echo "No Items Assigned";
};
That
moves from mysql_* to mysqli_* (check my syntax - most of the mysqli_* functions are the same but there are a few differences)
uses isset & !isset to determine which query to use
encloses your query string in ticks and quotes to help make sure you don't forget to quote something properly
fixes your or die catch (you were referencing $query which didn't seem to exist)
Related
I want to be able to select all rows where a value matches with the one I'm calling for in php
This is what I have for now and the only thing I get is the first row. Not the other rows.
<?php>
session_start();
require "db.inc.php";
$id = $_SESSION['userId'];
$sql = "SELECT followingId FROM following WHERE followerId=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
echo var_dump($result);
$followedId = $result['followingId'];
echo $followedId;
And $conn is the connection variable in db.inc.php
You must iterate through the results array you are fetching
while ($row = mysqli_fetch_array($result)) {
foreach($row as $field => $value) {
//do something with $field and $val
}
}
This is my table in my database. It should only contain one row.
I have this code, that checks if there is no data , if there is not.. The data is inserted, else it's updated. The problem is, that if i update only Brevet, the value of Baccalaureabt will disappear from my database. Any help?
Code:
if(isset($_POST['submit']))
{ $brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
if ($result=mysqli_query($con,$sql1))
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$sql2 = "UPDATE university SET Brevet = '$brevet' , Baccalaureatbt = '$baccalaureatbt'";
$result2 = mysql_query($sql2);
}
The issue is that you are setting both values, if however either $baccalaureatbt or $brevet is empty, it will be updated with a empty value, i.e the original value will be deleted.
There are multiple ways to avoid this, but one way to do it is like so:
$sql2 = "UPDATE university SET ";
if(!empty($brevet)){
$sql2 .= "Brevet = '$brevet'";
$first = 1;
}
if(!empty($baccalaureatbt)){
$sql2 .= isset($first) ? ", Baccalaureatbt = '$baccalaureatbt'" : "Baccalaureatbt = '$baccalaureatbt' " ;
}
$result2 = mysql_query($sql2);
To update the values dynamically, use the following code. Just add the values you want in the values array.
if(isset($_POST['submit']))
{
$brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
$result=mysqli_query($con,$sql1);
if ($result)
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$values = array("brevet","baccalaureatbt");
$sql2 = "UPDATE university ";
$n = 0;
foreach($_POST as $key => $val) {
if(in_array($key, $values)) {
$sql2 += ($n !== 0 ? ", " : 0);
$sql2 += "SET".$key." = ".$val;
$n++;
}
if($n > 0) {
$result2 = mysql_query($sql2);
}
}
}
}
Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?
To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}
I'm trying to display a "Welcome back, <name>." to my blog when I log in back. I'm using php to access the database, get the name and last name of the username currently in $_SESSION['username'], and then print it back in the index.
So the function to query the database is:
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = `{$username}`");
$row = mysql_num_rows($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}
Then the part of the html where it calls the function above:
<div id="menu">
<?php
$temp = $_SESSION['username'];
$real[] = get_full_name($temp);
if(isset($_SESSION['username']))
{
echo '<br />'.'Welcome back, '. $real['name'] . '.';
}
?>
</div>
The output of the above codes is:
Welcome back, .
var_dump($real) gives:
array(1) { [0]=> array(0) { } }
var_dump($real) after changing to mysql_fectch_assoc:
array(0) { }
Fixed: The error was not using the single quotes ' {$username} '
By changing them, it worked like a charm, cheers to all!
Curiously you are using mysql_num_rows to get the results of your query. This will only return the number of rows. You'll be better off using mysql_fetch_assoc to get the associative array of results.
You also need to change your backticks to single quotes around {$username} in the query.
Something like:
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = '{$username}'");
$row = mysql_fetch_assoc($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}
Your get_full_name() function should be like this:
function get_full_name($username) {
$real = array();
$query = mysql_query("SELECT `name`, `last`
FROM `users`
WHERE `user` = '{$username}'");
if (mysql_num_rows($query)) {
$real = mysql_fetch_assoc($query);
}
return $real;
}
Notes:
Use single quotes for the variable: '{$username}' instead of `{$username}`
Use mysql_num_rows() for checking if the result is not empty.
Use mysql_fetch_assoc() for retrieving the row.
Calling the function:
$temp = $_SESSION['username'];
$real = get_full_name($temp);
if (isset($temp) && count($real)) {
echo '<br />Welcome back, '. $real['name'] . '.';
}
Notes:
Use $real instead of $real[].
Check if $real empty with count().
Change this line $row = mysql_fetch_array($query);
Two issues I see.
1) You are using mysql_num_rows, not fetching the array of data from the database.
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = `{$username}`");
$row = mysql_fetch_assoc($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}
2) Looks like $real is a multi-dimention array in your code. Try this instead:
<div id="menu">
<?php
$temp = $_SESSION['username'];
$real = get_full_name($temp);
if(isset($_SESSION['username']))
{
echo '<br />'.'Welcome back, '. $real['name'] . '.';
}
?>
</div>
Notice I've removed the [] at the end of $real.
Use mysql_query() to get the result of running the query, then use mysql_fetch_assoc() to get individual rows.
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
var_dump($row);
}
Note that mysql_num_rows($result) will return the number of rows in a given result.
My code looks like this:
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
Problem is that when there is no row to select, nothing happens, my $row array is empty.
How can i have this present a message of "no row found" when no rows match the select?
try
if (mysql_num_rows($result) == 0) {
// Show message
} else {
// do your while stuff here
}
Use mysql_num_rows() to determine the amount of rows in your result.
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
if(mysql_num_rows($result) == 0) {
echo "No row found!"
} else {
while($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
}
}
if (mysql_num_rows($result) == 0) {
echo "Result is empty!";
}
You should've read the description of mysql_query, it gives you the answer: http://php.net/mysql_query
mysql_num_rows() only works on buffered queries. If you have potentially a large/huge result set you might switch to unbuffered queries and num_rows is not an option anymore.
You can test the return value of the first call to mysql_fetch_array(). If it's FALSE there were no matching records.
<?php
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo '0 rows';
}
else {
do {
echo htmlspecialchars($row['x']), "<br />\n";
} while($row=mysql_fetch_array($result, MYSQL_ASSOC));
}
The downside of this do { } while() is that the $row=mysql_fetch... code has been duplicated. But it's only a small doublet.
This method never seems to fail for me.
if(!$result = mysqli_query($con,"SELECT * FROM `picdb` WHERE `picid` = '$picid' ")){
// Enter you error message here.
} else {
// Do all your magic.
}