Selecting a row based on multiple column values? - php

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'];

Related

Counting Rows to be added and insert into table

I have a script that allows for multiple rows to be created on the page and then I need to have the rows counted on the post and then each row inserted into the table.
I have the GUI working to where users can add or remove rows as needed yet when I submit no data is being written to the table. I have tried altering the script for the post to be straight '$variables' and it works to write but only writes the first row.
I have attached the action script that I am using from WebLesson that works great for one field but for more than one I am at a loss for what to try.
//includes
include '----';
include '---';
session_start();
$number = count($_POST['name']);
echo $_POST['name'] . "<br>";
echo $number . "<br>";
if($number >= 1)
{
echo $_POST['pasid'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_POST['pasid'];
$name = $_POST['name'];
$dose = $_POST['dose'];
$dir = $_POST['directions'];
$time = $_POST['time'];
echo $i;
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO meds (id, name, dose, directions)
VALUES('".mysqli_real_escape_string($_POST["pasid"][$i])."',
'".mysqli_real_escape_string($_POST["name"][$i])."',
'".mysqli_real_escape_string($_POST["dose"][$i])."',
'".mysqli_real_escape_string($_POST["directions"][$i])."',
'".mysqli_real_escape_string($_POST["time"][$i])."') " ;
mysqli_query($conn, $sql);
}
}
echo "Data Inserted";
}
else
{
die("Connection failed: " . mysqli_connect_error());
}
I would like this to count how many rows were posted and then submit each row to the table.
Picture of the UI:
You can generate unique name attributes for each form element and then loop through them in PHP. The easiest way to do that would probably be increment a number at the end of the name attribute each time the user creates a new row. You will have to do that with Javascript.
var suffix = 0;
function addNewRow(){
...
<input type="text" name="pasid_${i}"/> //Add incriminating suffix
...
suffix++; //Increment suffix for next time
}
Then your PHP would look like
$suffix = 0;
while(isset($_POST['pasid' . $suffix])){ //Keep looping until no more POST value
//Process row $suffix, referencing all the data like $_POST['field_name'. $suffix]
$suffix++; //Increment suffix for the next field
}
Make sure the field you are checking for in the while loop is required or else the user might omit an input and the loop would terminate prematurely. You could also check multiple $_POST indexes in the while loop if non of the fields are required.

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";

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

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.

Cannot echo out the right result. PHP/MySQL

I want to make a code that check if a value in an exact column is equal to an 'neodobren', and if there is such value in the column to echo out the button 'Add Member' and Yes for each value. I've tried to do the following and it is not echoing the Yes:
I have the following MySQL table content:
UID Name Phone Email SchoolGymnasium City Password Status
1 neodobren
2 neodobren
and I have the following PHP code inside the HTML index page:
$con = mysql_connect("localhost","****","****");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
include("../../sql.php");
session_start();
$zaqvki = mysql_query("SELECT * FROM Directors WHERE Status='neodobren' LIMIT 1");
if(mysql_num_rows($zaqvki) > 0) {
echo '<div align="right">Add Member</div><br>';
// display data in table
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($zaqvki)) { //$zaqvki was $result, before a guy comment me this...
echo "Yes";
} }
else {
echo "No";
}
It is showing only the button add member, and not showing the Yes, which must be echo-ed.
Use mysql_fetch_assoc to get an associative array and make a comparison on each row of a certain column:
while($row = mysql_fetch_assoc($result))
{
if($row['Status'] === 'neodobren')
echo "Yes";
else
echo "No";
}

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

Categories