Display one result(cell) from mysqli query - php

I have been trying to rack my brains on this one for a while and the documentation on both MySQL and MySQLi is confusing me. Would it be possible to get any help?
I have a table called track_table and it contains two rows hash and track
hash | track
sdfsdfsdfsdfsdfsd | Azelia Banks - 1991
I want to display the track name but I don't know how to. I have tried 'mysqli_fetch_assoc' and various other functions but nothing. Here is the query I have so far.
$hash = $_GET['sub'];
$check_track = "SELECT track FROM track_table WHERE hash = '.$hash.' ";
$track_res = mysqli_query($mysqli, $check_track) or die (mysqli_error($mysqli));
$result = mysqli_fetch_assoc($track_res);
echo $result['track'];
I just want to be able to display the track name on a webpage.
I know I haven't implemented any security features and I'm taking data straight from the user, I shall do this later, once I have fixed this problem.

There's a problem with the string-literal . variable . string-literal part of your script.
if ( !isset($_GET['sub']) ) {
die('missing paraemter sub');
}
$check_track = "
SELECT
track
FROM
track_table
WHERE
hash = '".mysqli_real_escape_string($mysqli, $_GET['sub'])."'
";
$track_res = mysqli_query($mysqli, $check_track) or die (mysqli_error($mysqli));
$result = mysqli_fetch_assoc($track_res);
if ( !$result ) {
echo 'no such record';
}
else {
echo $result['track'];
}

try this one
$hash = mysql_real_escape_string($_GET['sub']);
$check_track = "SELECT track FROM track_table WHERE hash = '.$hash.' ";
$track_res = mysql_query($check_track) or die (mysql_error());
$result = mysql_fetch_assoc($track_res);
print_r($result);
be sure about the names of table, column or input type.
i hope it will help you.

Related

php statement for multiple users not working

I am helping in some PHP design for a friends text game and have come to a stump.
I have scheduled a cron job to call the following page / following code, which is working correctly
<?php require("connect.php"); ?>
<?php
$sql = "SELECT id, name, health FROM users";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$id = htmlspecialchars($row->id);
$name = htmlspecialchars($row->name);
$health = htmlspecialchars($row->health);
$sql = "SELECT * FROM property WHERE living='1' AND ownerid='$id'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$OwnerName = htmlspecialchars($row->ownername);
$OwnerID = htmlspecialchars($row->ownerid);
$RaidPropBonus = htmlspecialchars($row->raidperc);
$RaidPropMoney = htmlspecialchars($row->raidcash);
$PropertyLvl = htmlspecialchars($row->proplvl);
$Living = htmlspecialchars($row->living);
if($PropertyLvl == '5' && $Living == '1'){
if($health < '100'){
$result = mysql_query("UPDATE users SET health=$health + '1' WHERE id='$id'")
or die(mysql_error());
} else { }
} else { }
}
}
?>
Although this only works for ONE user only. I cannot understand why this is. Any other logged in / out accounts that have met the criteria have been ignored. I can maybe only think I am missing a loop? As the ID that is being met first is number 1 and it has stopped there?
Anybody advice at all maybe?
UPDATE - It seems correct I need to get a loop in there, but am so far failing to get this loop working correct. No matter where I seem to amend / add a loop it does not help. Please may somebody suggest anything?
UPDATE2 - As requested, updated with the new version of loop
For what I've understood, the loops should be made on the mysql_fetch_object that will get the each row from the query.
Take a look at the snippet
<?php
require("connect.php");
// here prepare the $userQuery (the one that fetches all users)
// then the first loop that will read each usew row
// AFAICT this should afect all script
while($userRow = mysql_fetch_object($userQuery))
{
// prepare data fetched from the $userQuery
// prepare the $propertyQuery (the one that fetches all properties of the user)
// then the second loop to read all user property rows
// and this will afect the updates
while($propertyRow = mysql_fetch_object($propertyQuery))
{
// prepare data fetched from $propertyQuery
// add logic here
}
}
?>
Also #Matthew Carpenter had a valid point, that mysql_* is deprecated, you should consider in using mysqli_*, or in my opinion take a look at PDO

PHP/mysql fetch multiple variables in array

I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.

Display single result from database where ID matches using mysql and php

I am having some trouble displaying a single field from the db based on an ID number.
I want to trying to display the "C_Type_of_Referral" if the ID matches. I am sure the code is a mess of crap but I am still at the VERY early stages of learning how to do things in mysql and php.
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = '70'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($C_Type_of_Referral) = mysql_fetch_array($result);
Then I am trying to display the result using the code below:
echo ((isset ($_POST['C_Type_of_Referral']) && $_POST['C_Type_of_Referral'] == 'AS') || ($C_Type_of_Referral == 'AS'));
The code above returns the value of 1.
echo ($_POST['C_Type_of_Referral']);
The code above returns nothing.
Where am I going wrong?
Thanks for any help!
Let me start with: Use mysqli instead of mysql, especially when you are starting. Mysql is getting outdate, so start with the right one :)
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = 70 LIMIT 1";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$fetch = mysql_fetch_assoc($result);
echo $fetch['C_Type_of_Referral']; // <- this is what you are looking for
if( $fetch['C_Type_of_Referral']=='AS'){ echo 'AdServices'; }
elseif( $fetch['C_Type_of_Referral']=='VS'){ echo 'VisServices'; }
else{ echo 'Nothing of the kind'; }
Things I've done:
- removed quotes arround 70. Integers should not use quotes.
- Added 'limit 1'. This will speed things up in the long run. If you want 1 line, use limit 1
- Changed fetch_array to fetch_assoc ( you'll have to find out why yourself ;) )
Small note: keep table and columnnames lowercase, some systems might give you troubles when you use uppercase characters

Fetch Multiple rows data from Server using PHP Code

Getting record for first row, but want to get all record(s) available in table for a Particular MemberID
order_fetch.php
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("android");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE MemberID = '".$strMemberID."' ";
$objQuery = mysql_query($strSQL);
$obResult = mysql_fetch_array($objQuery);
if($obResult)
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["MemberID"] = $obResult["MemberID"];
$arr["TotalAmount"] = $obResult["TotalAmount"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo json_encode($arr);
?>
This does not look like a great example of a question that will help the community here. Looks to me you'll have to debug your code to see what's going on.
Do so and while at it give us the content (and type) of the resultServer object and the Data object. Is that Data object even holding a collection?
You can't expect us to implement this or fix this without at least knowing the implementation of these objects? Not to mention the actual json you get from your server implementation.

PHP not returning results from MySQL query as expected

I'm trying to create a variable which is dependent on some information from the database. I'm trying to generate a $path variable which stores a path, depending on what information is recovered from the database.
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
while ($row = mysql_fetch_row($temp)){
global $groupID;
foreach ($row as $field){
$groupID = $field;
}
}
....
$path = "C:\WAMP\www\project\\" . $groupID;
$dir_handle = #opendir($path) or die('Unable to open $path');
The idea behind this is that $variable is set before the PHP is run, however it's set to 00001 for testing. The ideal situation is that $path should equal C:\WAMP\www\project\00001\. Currently, when I echo back the $path all I get is the original path without the $groupID added to the end.
I also receive the message "mysql_fetch_row() expects parameter 1 to be resource" but I've used this method for retrieving information before and it worked just fine, and I set up my table in the same way so I don't think the issue is there.
I have a feeling I'm missing something obvious, so any help is appreciated. It's not for an assignment or anything school related (just trying stuff out to learn more) so knock yourselves out with correcting it and explaining why :)
In addition, only one memberID will ever be a match to the $variable, so if there's an alternative way to fetch it I'd appreciate knowing.
Oh, and I know my variable names are shocking but they're only that on here, on my actual code they're different so no criticism please :p
EDIT: The SQL query is correct, after following BT634's advice and when running it on phpMyAdmin I get the groupID I want and expect.
mysql_select_db("table", $linkid)
should actually be
mysql_select_db("database_name", $linkid)
since you are connecting to the database that contains the table and not the table itself.
Also, try mysql_result($temp,0) instead of the while loop
First of all, you're not specifying what database to connect to in your connection - you're specifying what table. You might also want to check how many rows your query is returning:
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
echo mysql_num_rows($temp);
If it's still complaining about $temp not being a valid resource, change your MySQL connection code to:
// Establish connection
$con = mysql_connect("localhost","peter","abc123");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("my_db", $con);
// Make your query
$result = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'");
// Find out what the value of the query is (i.e. what object/resource it is)
var_dump($result);
Once you know that MySQL is returning valid data, extract the values you want. You don't have to use globals:
while ($row = mysql_fetch_row($temp)){
$groupId = $row[0];
}
// Use $groupId however you please...
One thing to bear in mind is that mysql_fetch_row will return
array
(
0 => '...'
)
Whilst mysql_fetch_assoc will return:
array
(
'groupId' => '...'
)
Find out what query it's definitely running, and paste that into a normal MySQL client to make sure your query is correct.
Just do this after defining "$variable"
exit("SELECT groupID FROM table WHERE memberID='$variable'");
Then copy the output into a MySQL client (or MySQL from the command line).
Try something like this:
global $groupID;
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$sql = "SELECT groupID FROM table WHERE memberID='$variable'";
$temp = mysql_query($sql, $linkid) or die(mysql_error());
$row = mysql_fetch_row($temp);
if ($row) {
$groupID = $row['groupID'];
}
If you are retrieving a single value, and it is guaranteed to be unique, then the loop structures are unnecessary. I've added a check to ensure the query exits with an error if there's a problem - it is ideal to do this everywhere, so for example do it with mysql_select_db too.

Categories