How can I SELECT field FROM table WHERE id=variable? - php

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.

Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

Select data from MySQL DB based on the URL example (www.example.co.uk/essex.php)

I am very new to php and I am looking to create dynamic pages.
Basically If a person lands on www.example.co.uk/essex.php I would like to be able to add something like <h1>Company In <?php echo $row['County']; ?> so that it would show
Company In Essex when Live and save time if I need to duplicate the page for another county or town.
So far I have setup a database in phpmyadmin
Picture of Table
My code so far to grab the table is;
$dbconnect = mysqli_connect("HOST", "USER", "PASSWORD", "DB");
if(mysqli_connect_errno()) {
echo "Connection Failed:".mysqli_connect_error();
exit;
}
$count_sql="SELECT * FROM areas";
$count_query=mysqli_query($dbconnect, $count_sql);
$count_rs=mysqli_fetch_assoc($count_query);
and then on www.example.co.uk/essex.php
<?php
do {
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))
?>
But where I have gone wrong is it pulls all the data from the table for County where I only wish it to pull the county of Essex.
Please forgive me for explaining this badly.
UPDATE -
$row = url2content();
extract($row);
function url2content($url = NULL){
if(is_null($url)){
if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"]){
$url = $_SERVER["REQUEST_URI"];
}elseif(isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"]){
$url = $_SERVER["PATH_INFO"];
}
if (substr($url,0,1) == '/'){
$url = substr($url,1);
}
}
if (DEBUG_MODE){
echo ('URL requested: "'.$url.'"<br>');
}
function get_towns($county){
$query = sprintf("select townName from " . AREAS_TABLE . " where countyName = '%s' order by rand() LIMIT 0,24" ,mysql_real_escape_string($county));
$res = mysql_query($query);
if(!$res){
printf("Unable to query ".AREAS_TABLE." table: %s \n", mysql_error());
}
$html="";
while($row = mysql_fetch_assoc($res)){
$html.="<li>".stripslashes($row["townName"])."</li>\n";
}
return $html;
}}
You have to use WHERE clause in your query in order to select a specific country from your db
SELECT * from table WHERE felid_country=$count_rs['County'];
You can use strpos() to match the County (eg.essex) with url $_SERVER['REQUEST_URI'] (eg.www.example.co.uk/essex.php) in your case.
Just like this
<?php
do {
if(strpos($_SERVER['REQUEST_URI'],$count_rs['County'])!=false)
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))

Date insertion to php table via php failing

i have a cart displayed and the user has to select the date of delivery from the calendar widget and click on Confirm button. on submit, the order cart should be populated along with the entered date of delivery.
the code i used is:
<?php
echo "<form action='' name='form1' >";
//some disaply codes here
echo "Choose the Date of delivery<input type='date' name='date'>";
echo "<input type='submit' class='btn btn-default' name='final_submission' value ='Confirm Order'>";
echo "</form>";
?>
the code for insertion is:
<?php
if (isset($_POST['final_submission'])){
error_reporting(E_ALL);
ini_set('display_errors', 1);
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
$result=mysqli_query($conn, $query);
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.',
'.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
?>
the orders table s not getting populated. I cant put my finger on the error. plz point it out
EDIT: the orders table is getting poplulated, but the del date field is coming blank...Please let me know how to pass the date variable correctly, as clearly that is the issue
I am not sure what you are trying to attempt to be honest. Your code blocks lacks a lot of stuff. For instance:
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
What results? Where do you define them? Are that results from the query you specified there, cause surely you aint executing it. Thus the result will be 0 and will not be executed.
Also the problem is with this query it will go through every row of the cart, this means also you ll grab carts that aint belonging to your costumer, specify.
So your code should be something like
$query="select * from cart";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
// yadi yadi yadi .. code code code
edit
Let me try to rework this out for you with propper indenting.
if (isset($_POST['final_submission'])){ // check if the button is correct
// error_reporting(E_ALL); <-- canceling this out for now
// ini_set('display_errors', 1); <-- canceling this out for now
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
if (empty($date) || $date == ''){
echo 'the date is not set, please check if parameter is filled in';
} else { // if it wont pass this point, you wont get an enormous output of unidentified indexes
$query="select * from cart";
$result=mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$date = stripslashes($_POST['date']); // just to play it safe define it again
if (empty($date) || $date == ''){
echo 'something went wrong with the date';
}else{
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.','.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
}
}

Fetching rows in array using SELECT * FROM table WHERE IN

Hi I am trying to fetch data from a particular coloumn from all rows.
Eg Situation:
DB Data: id, fbid, name
$sql = 'SELECT id FROM table WHERE table.fbid IN (1234,5678,4321)';
$sql_run = mysql_query($sql);
$sql_fetch = mysql_fetch_assoc($sql_run);
print_r($sql_fetch);
This returns the data when I test it using Sequel PRO or PHPmyAdmin.
But when I print the array it only displays one value.
Can you help me with a solution or tell me where I'm going wrong?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Before using a function, or - at least - when it does not what you expect - it's always a good idea to read the function description in the manual page.
PHP provides extremely easy access to its manual pages. All you need to type in the address bar is php.net/function name. It takes less time than typing whole question on Stack Overflow, yet you will get exactly the same answer. Think of efficiency.
You need to loop through each row
$sql_run = mysql_query($sql) or die(mysql_error());
while ($sql_fetch = mysql_fetch_assoc($sql_run)) {
print_r($sql_fetch);
}

Selecting a row based on multiple column values?

I'm working on a little system for SecondLife which involves a bit of heavy use of databases & I've run into a problem I can't for the life of me solve.
I'm trying to run a query that selects an entire row based on two different column values. I'm using the $_GET[''] call to identify which details I need, and then I need to pull all the data from the entire row and echo it onto a blank page.
Now, I got it to work at first, but it was pulling ALL the rows created by a UUID and echoing them, when I only needed a specific. Then I tried to get it to work with a second identifier (which is a column called 'field' for the purpose of testing), and that's pretty much where I lost it.
I just need to select one row that has two exact values, and I need it to be draconian so it only selects a row that has both and not just one of the two.
Any ideas?
Script enclosed (don't mind the mess or the commented out code which I kept for reference; I am going to clean the script once I get it working!)
<?php
// Get key from the parameter.
$avatar_key = $_GET['key'];
// Quest params.
$questname = $_GET['questname'];
$questid = $_GET['id'];
// Connect to the database. $con holds connection info.
$con = mysql_connect("localhost","user","pass");
// Error checking.
if(!$con)
{
die('Could not connect: '.mysql_error());
}
// Select the DB we want.
mysql_select_db("yyyyy_slcom",$con);
// Build the query.
$query = "SELECT * FROM sldb_data WHERE sldb_data.uuid = '$avatar_key' AND sldb_data.field = '$questname'";
/*$query = "select * from (
select uuid, field, value, progress, ROW_NUMBER() OVER (PARTITION BY uuid ORDER BY progress DESC)
";*/
// Run the query, store the result in variable $result.
$result = mysql_query($query);
if(!result)
{
die('Error: ' . mysql_error());
}
// Check how many rows we got back with our query.
$rows_returned = mysql_num_rows($result);
echo $row['field'];
// If we get anything back,
if($rows_returned > 0)
{
//echo $row['field'] . ' was found.' . $questname;
/*if(!$row['field'])
{
echo 'You are not on this quest yet.';
}
elseif(($row['field']) && ($row['value'] == "notstarted"))
{
echo 'This quest hasn\'t started yet.';
}
elseif(($row['field']) && ($row['value'] == "started"))
{
echo 'You are on quest: "' .$row['field']. '"';
}*/
/* $fields = mysql_list_fields("tenaar_slcom","sldb_data");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if(in_array($quest, $field_array))
{
echo 'Your quest is ' . $row['field'];
}
elseif(!in_array($questname, $field_array))
{
echo 'You are not on this quest yet.';
}
elseif((in_array($questname, $field_array)) && ($row['value'] == "notstarted"))
{
echo 'You have not started quest "' .$row['field']. '" yet.';
} */
// cycle through and print what we got.
//while($row = mysql_fetch_array($result))
//{
//echo 'Quest name: ' . $row['field'] . ' | Progress: ' .$row['value'] . '<br />';
//}
}
/*else
{
echo 'You are not on this quest yet.';
}*/
// Close the connection.
mysql_close($con);
?>
You appear to be missing a step in-between the time you get the number of rows and when you print out the field. You need to actually store the results of the query in the $row array.
$rows_returned = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $row['field'];

Categories