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.
Related
First and formost, yes i know PHP5.6 is deprecated version, but i want to stick with it and fully learn PHP for myself, before updating to MySQLi.
I'm trying to make a text based game running MySQL and PHP, and currently trying to create a system that:
1.Gets information from user table, username and total actions done (+)
2.At the certain timestamps save all usernames and actions into separete table (-)
3.Resets actions column to 0 for ALL players. (+/- planning to use a mysql trigger and/or cron-job)
My questions:
2) How would you suggest me to insert usernames into seperate table? (only idea i come up is to explode array somehow get variables and sumbit to mysql, question is how to do so? )
3) regarding this number 3, would you suggest something else then triggers or cron-jobs?
Code example bellow
<?php
include './config/connect-db.php';
$result= mysql_query("SELECT * FROM user WHERE actions > 100 ORDER BY
actions DESC LIMIT 5");
while($row = mysql_fetch_array($result)){
if ($row['u_dmisijos'] >= 100) {
echo '<li>'.$row["u_name"].' ('.$row["actions"].')<br>';
} // if actions
} //while loop
?>
EDIT:
MySQL includes a lot of columns, there are only 2 specific I'm focusing on, u_name (username) and actions (actions).
EDIT2:
What i am expecting on second table: ID (AI), username of player with the most action points, username of player with second action points etc. And Datastamp.
expected SQL
ID, nr1, nr2, nr3, nr4, nr5, Datastamp.
Cheers!
I am not sure this will work or not as I have not tested it. But, I hope you might get a general idea.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT * FROM user WHERE actions > 100 ORDER BY actions DESC LIMIT 5";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$q = "INSERT INTO `new_table` (`u_name`, `actions`) VALUES
($row['u_name'],$row['actions'] )";
mysql_query($q);
}
?>
Regarding resetting all actions to 0 you can create a functions like:
function resetActions(){
//update actions to 0
$q = "UPDATE table_name SET actions = 0";
mysql_query($q);
}
Now, whenever you need to reset it you can call this function. Or you can call this function in cron job as you required.
I'm a Mysql/php novice and I'm trying to get several results of one query.
I have a db named "my_db", who has a table named "my_table". This table has only one column named "fruits". I inserted some elements in items like banana, pineapple, coconuts and apple.
I would like to display all this items so I tried this code:
$sql = 'SELECT items FROM my_table';
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error());
$data = mysql_fetch_array($req);
mysql_free_result ($req);
echo $data['items'];
But this only show me the first element of the column "items" (here, banana).
How can I show a list of all the elements ?
Thanks in advance !
If you use mysql, then you need to create cycle, for excample "while cycle":
$sql = mysql_query("SELECT * FROM lietotajs");
while($row = mysql_fetch_array($sql ))
{
echo $row['ID'];
}
You have to run while loop after running the query, other wise it will restrict to single.
Try to do this, not tested. Hopes it will help
$sql = 'SELECT items FROM my_table';
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br/>'.mysql_error());
while($data = mysql_fetch_array($req)){
echo $data['items'];
}
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";
}
I am trying to learn php and came across a task which i have need help with.
Background information - I have a postgresql database which has
multiple tables.
What I need - When I enter anything in the form on my HTML page, i
need to extract all information from all the tables that contain
information related to what I have entered.
Example - Suppose I enter food poisoning in the form. I need to access
all the tables and extract the different information related to food
poisoning.
My code: (the connection part is not being posted as it works fine)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.bacteria WHERE disease = $1');
// if (pg_numrows($result) == 0) {
// $result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.virus WHERE disease = $1');
// }
//$sql = "SELECT * FROM Project.bacteria WHERE disease=";
//$result = pg_query($dbh, $sql);
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
?>
For the above code, when I enter food poisoning it searches just one table i.e bacteria and returns the related information ( here as a test i have taken just information at row position 1 and row position 2.)
Since there are multiple tables, like a table drugs that stores information of drugs used to cure food poisoning, i would want to extract that information from the respective table.
Any help would be appreciated.
try this one
SELECT * FROM bacteria WHERE disease = ''
UNION ALL
SELECT * FROM drugs where desease = ''
but i think the best way is to normalize you tables. :)
I am building a simple website that helps students and instructors in universities.
I am facing a problem about the following query:
An instructor retrieves the students' IDs and names who are enrolled in the course he/she teaches.
I have the following tables, followed by their fields:
Enrollment (CourseCode - StudentID - Grade)
Studnet (ID - Name)
As you can see the only connector between the two tables is the student ID.
The code that I wrote is
<?
session_start();
$COCODE = $_SESSION['GlobalCode'];
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$COCODE' ") ;
$row11 = mysql_fetch_array($result11);
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Student where StudentID= '$StID' ") ;
echo "<table border cellpadding=3>";
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
echo "</table>";
?>
What I am trying to do is to retrieve the course code from the Enrollment table and then retrieving the students names through the ID.
The problem is that I got the following message:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
I hope you can help me solving the problem.
Thanks
Have you tried to narrow down which of the queries is causing the problem? That would be your first step. Some other pointers:
you need to check that each SQL query is successful and returning a valid value before using it in the next query... otherwise that query will cause an error.
Try using: mysql_query ($your_query) or die ('Error: '.mysql_error ()); for each query for a more detailed error message. (for debugging only, not for production)
That error usually means there's something wrong with your query, or perhaps you are not connected to your database. If its the first problem, try changing your query to this:
$result11 = mysql_query("SELECT * FROM `Enrollment` WHERE `CourseCode` = '$COCODE' ");
Otherwise, check your database connection.
Finally, I solved it.
I did the following changes:
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$InstID' ") or die ('Error: '.mysql_error ());
echo "<table border cellpadding=3>";
while($row11 = mysql_fetch_array($result11))
{
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Students where ID = '$StID' ") or die ('Error: '.mysql_error ());
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
}
echo "</table>";
mysql_close($con);
?>
Thanks