Fetching rows in array using SELECT * FROM table WHERE IN - php

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);
}

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

PHP return results from MySQL Query

I'm fairly new to PHP, but here is my issue, I am trying to get the results from a SQL query to display on the page, but I'm not getting anything returned.
Here is the code that I'm currently working with:
<?php
$con = mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno()) {
echo "Connect failed: ". mysqli_connect_error();
}
$de= $con->real_escape_string($_GET["decode"]);
$sql = "select * from FG99_URL where short='".$de."'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo "url: " . $row["url"]. " - fb_url: " . $row["fb_url"]."<br>";
$url=$row['url'];
$fb_url=$row['fb_url'];
$fb_type=$row['fb_type'];
$fb_title=$row['fb_title'];
$fb_description=$row['fb_description'];
$fb_image=$row['fb_image'];
$petpro=$row['petpro'];
echo $fb_url.'test 1</br>';
echo $row['fb_url'] . "test 2</br>";
print $fb_url."test 3</br>";
print $row['fb_url']."test 4</br>";
}
?>
<head>...
This is what I get returned:
url: - fb_url:
test 1
test 2
test 3
test 4
Any help would be appriciated.
Do a var_dump($row) and see what is in the row variable.
That will help to see whether you have those data in those returning data set.
Based on the output, you are getting some data and returning data might not have the columns you are looking for.
Hope it helps.
Check your database first.
After set sql query, try this code:
$sql = "select * from FG99_URL where short='".$de."'";
echo $sql;
Copy and paste sql query into DB client like mysqladmin.

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.

Use multiple keywords to display results from 2 tables

EDIT......I have a normalized database which is based on a learning environment.
I would like to be able to search for a selection of keywords which are in a table called 'C_Search' and use them to pull up the course details which stored in 'C_Info'. I have a basic search function but it is driving me crazy with how to get the keywords involved as I am new to all this and trying to learn as I go along...sometimes we need help
These are the relevant tables and the fields in them.
C_Info
Course_ID
Course_Name
C_Description
C_Duration
C_Cost
C_Entry_Req
C_Assessment_Type
C_Progression
C_Type
C_Search
Course_ID
C_Key_Words
C_NLC_Ref_No
Awarding_Body
C_UCAS_Code
There are a list of keywords separated by a coma. I would like to use them to allow users to search the database for available courses.
I know I have posted this before but some of the answers were confusing and I'm struggling to learn as it is.
<?php
mysql_connect ("localhost", "jimbooth_test","test1") or die (mysql_error());
mysql_select_db ("jimbooth_groupproject");
// first part of the main query (with dummy WHERE operator so you can then use AND operators)
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
// query the keywords
$res1 = mysql_query("select keyword from C_Search") or trigger_error(mysql_error()
// loop through rows and add conditions to the main query
while ($keyword_row = mysql_fetch_assoc($res1)) {
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
}
$res2 = mysql_query($query);
die($query);
if (mysql_num_rows($res2) <= 0) {
// no results
echo 'Sorry, No results found.';
} else
while ($row = mysql_fetch_array($res2)){
echo '<br/> <B>Course Title:</B> '.$row['Course_Name'];
echo '<br/> <B>Course Info:</B> '.$row['C_Description'];
echo '<br/> <B>Duration:</B> '.$row['C_Duration'];
echo '<br/> <B>Entry Requirements:</B> '.$row['C_Entry_Req'];
echo '<br/> <B>Course Cost: '.$row['C_Cost'];
echo '<br/> <B>Course Progression: '.$row['C_Progression'];
echo '<br/><br/>';
}
?>
Your SQL query is failing:
"select keyword from C_Search"
Which means that $res1 is not a result. Instead, it is a boolean FALSE value. mysql_fetch_assoc expects a resource. Are you sure that C_Info exists and that you haven't made any typos?
Try adding:
$res1 = mysql_query("select keyword from C_Search") or trigger_error(mysql_error());
Tell us if any errors are spit out onto the screen.
PS: The people telling you remove the WHERE 1 don't seem to realize that you're doing this:
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
further down the line. Although I do agree that you should probably use WHERE 1 = 1 as that is the most commonly used "always true" condition that gets used when a query is being constructed dynamically :)
I think you connection to DB is not set properly kindly check the connection by
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

{if...else} how to display an image if a mysql field equals ex.1

i have a question:
i have a mysql table that has values such as pages_viewed that increments every time a user accesses a page such as 1,2,3 etc.
My question is simple how do i display an image when the field equals or is more than 1?
like
select pages_viewed from table;
if field pages_viewed > 1 than echo images/image.png
pardon my php i'm not too good at it.
i've been reading here and in other forums but all i can find is drupal or wordpress.
something like
header('Content-Type: image/png')
echo file_get_contents(images/image.png)
Here is everything basically short of database connection, table name, field name.
mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("select * from table");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
# Any other code to post the page information
if($row['pages_viewed'] > 0) echo "<img src='images/image.png' />";
# Any other code to post the page information
}

Categories