Display more than one row from SQL SELECT - php

I want to display all of the rows shown in the picture where CID = 1.
Here is my PHP code with SQL:
`
$contractCount = 1;
$sql = "SELECT categories.categoryID
FROM categories
LEFT JOIN link
ON categories.categoryID = link.categoryID
WHERE link.CID = '$contractCount'";
$res = $con->query($sql);
if (!$res) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_array($res)) {
echo $row['categoryID'];
}
Here is an image showing the table in PHPMyAdmin called categories.
So I need output as ITSM, Mar and HrAd but I am only getting ITSM and not the rest.
EDIT 1: The LEFT JOIN makes no difference here, the link table has no bearing on the SELECT statement
EDIT 2: I have solved the problem, my mistake was that I had the table names the wrong way round in the SQL query.

You need to use the function mysql_fetch_row, this will fetch a row and move the pointer to the next one.
while ($row = mysqli_fetch_row($res)) {
echo $row['categoryID'];
}

Related

mysqli gives 0 result for query in php but gives correct result in terminal

I've got two tables and an association table of those two. I'm trying to run a query which gives my desired result running the code from terminal, but gives zero or unknown column result if executed from php.
This is my query:
$result = $mysqli->query("SELECT * FROM projects p
JOIN projects_groups pg on p.projectid = pg.projectid
JOIN groups g on g.groupid = pg.groupid
WHERE p.projectid = 'bestproject'");
Running the code exactly like above gives me back 0 result. If i switch 'bestproject' with a variable it gives me back an unkwown column bestproject error.
What's wrong with my query?
UPDATE: I had a stupid error in my function that was recieving the result, which caused my confusion. The receiver function was showing an empty array when the query was successfull, and also the function that handled the query was showing empty or failed result when the query was wrong (Not the one above). I kept searching for the error in the query instead to look at somewhere else. Sorry for wasting your time.
Everything you have done there is selected what tables and content. You need to have a php function that writes out the content as well.
Example:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
As you can see so does the echo writing out the content of the tables. You also can make so you don't have to use $row['id'] Just save it in a another variable:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$first = $row['firstname'];
$last = $row['last'];
echo "id: $id - Name: $first $last<br>";
}
} else {
echo "0 results";
}
Of course you need to have some content in the tables
The first problem does not make sense to me. The unknown column error is caused because you didn't use the single quotes so MySQL will try to find a column with your variables name instead of handling it as a value.
$result = $mysqli->query("SELECT * FROM projects p
JOIN projects_groups pg on p.projectid = pg.projectid
JOIN groups g on g.groupid = pg.groupid
WHERE p.projectid = '".$argument."'");
To avoid SQL injection it's better to use PDO to pass arguments. http://php.net/manual/en/book.pdo.php
Thank you for the answers, you helped me to look somewhere else.
The truth is that i've made a mistake somewhere else. I was loading the result into an array while i only wanted to get one result, and the function that recieved it was actually trying to get data out of a different variable...
It's kinda embarassing, but i've spent hours to figure it out, so i had to ask.
Sorry and thanks for the help!

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Getting the table name of a row from a mysql query that grabs from multiple tables

I have some PHP/MySQL code that pulls data from multiple different tables (using Inner Joins). It looks something like this:
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
echo $row[1];
}
So the code is simple enough, but what I want to do is echo the table each row is in inside of that while loop, since it could be in one of 2 tables.
I saw there was some old mysql functions like mysql_field_table and mysql_tablename that would do the trick, but they all seem to be deprecated.
Would appreciate any advice on how to accomplish this.
You could select the data with a special identifier for each table instead of using *
select table1.row1 as t1r1, table2.row1 as t2r1,..... from .....
And inside php you could look for the strings t1 and t2 and do stuff accordingly.
What you can do is echo more than one field from your result table (which hopefully now contains information from both the tables.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data))
{
echo $row[1] . " " . $row[2];
}
...and then $row[3] etc...
Or access the column name/field by the column name or alias provided by AS.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($data))
{
echo $row["c_name1"] . " " . $row["c_name2"];
}
Where "c_name1" and "c_name2" are your column names.
Use an AS keyword to rename all columns.
$select_clause = '';
$tables = array('tblA', 'tblB');
foreach($tables as $tbl) {
mysql_query('SHOW COLUMNS FROM ' . $tbl);
while ($row = mysql_fetch_assoc())
$select_clause .= '`'.$tbl.'`.`'.$row['Field'].'` AS `'.$tbl
.'_'.$row['Field'].'`,';
}
$select_clause = substr($select_clause, 0, -1);
mysql_query('SELECT '.$select_clause.' FROM /*...*/ ');

loop problem within a statement

i hope someone can help about to scream!
basically I am trying to do a few things with the statement below;
First i want to check if the user id exists in member_categories_position.
If it Does i want then to exclude all entries from the second statement where member_id equals all results from the first statement
the third statement is the else statement that displays if the member_id is not present in the member_categories position.
PROBLEM - the result from the first system loops fine, however when i try and insert into the second statement (!='$memid') is produces no results and has no effect. I think the problem is that $memid is a looped result.
How do i get the second statement to say that any member_id that is in member_categories_position will not show in that statement?
$sql2 = "
SELECT *
FROM member_categories_position a
JOIN member_users b
ON b.id = a.member_id";
$rs2 = mysql_query($sql2);
while ($row = mysql_fetch_array($rs2))
{
$memid = "".$row['member_id']."";
}
if(mysql_num_rows($rs2) != 0)
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
AND member_categories.member_id !='$field'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "result excluding member ids from the first statement";
}
echo "<div class=\"clear\"></div>";
}
else
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "Result with all member ids";
}
echo "<div class=\"clear\"></div>";
} } <-- (second is a stray from original post)
$memid is not in scope since it appears to be defined inside the loop. Try defining $memid = ''; at the top of your script.. like this.
$memid = '';
$sql2 = "
SELECT *
That way it will be defined when you use it below..

Categories