I have searched all over the internet and have found various "helpful" tips about how to do a column sum with PHP and a MySQL table. The problem is that I can not get ANY of them to work.
Essentially I have a very simple database with 2 users. The table within the database is called users and each entry has a 'Name' and a 'Total Steps'. All I want to do is display the result of the total steps of each user and then a sum of their steps.
Here is my code:
<?php
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
$row = mysql_fetch_assoc($steps);
$sum = $row['value_sum'];
?>
However, I get this error upon loading the page:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /nfs/nfs4/home/msnether/apache/htdocs/st.php
Since I don't know PHP or MySQL very well yet, this is quite frustrating and I would appreciate any help.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST
$conn = mysql_connect('database_server','database_username','database_password');
SECOND : Execute a database connection.
mysql_select_db($conn,'database name');
THIRD : Create a Query(you may insert your query here)..
$sql= mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = mysql_fetch_array($sql)){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
If you "Do not know PHP and Mysql well" then, knowing or die(mysql_error()) will be a pretty useful tool for you in the future. Just add it here, and see what mysql will make you understand politely.
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users") or die(mysql_error());
Related
This is my MySQL statement, I want to search record by status or description.. this statement works fine in phpMyAdmin, but it is not working in php script.. Any Suggestions Please..
$result = mysqli_query($mysqli,
"SELECT * FROM `statuses`
where statuses.`status` LIKE '%$search%' OR
statuses.`description` LIKE '%$search%'");
I hope you write everything correct but there may be error in how you fetching data. Here are the things you need to check.
check your connection string
If you are retrieving data then use something like below
while($row = $result->fetch_array())
{
echo $row['example_col_name'];
}
You can do one more thing if everything alright store your query to a variable and echo out that one then you will see what query is passing .
I've read all the questions or at least lots of them and what I see is lots of code that for a beginner like me doesn't help a lot...
Probably, you will say that I'm a noob to start making my own webpage with login, register, and all that stuff and I also see people talking about giving up on mysql stuff to avoid sql injection and all of those security details.
All I need to know is a simply a thing about 1 code I'm getting wrong.
$mail = mysql_query("select email from users where username = '".$_SESSION['username']."'");
This is the variavel I have made to get the email of the actual user in the logged in session.
When I put your email is <?php echo"$mail".; ?>, it gives me the next detail:
your email is Resource id #8.
Why am I getting that? I've made the variable in a place with session started but I don't get what I have in that column on the specified user.
Sorry if I shouldn't post that in here, but I really don't see anyone with the same problem. All I see is complex codes and I really don't understand a lot of that.
I'm still a beginner, so if you guys can give me an hand, I will be grateful.
You have to use mysql_fetch_[array|object|assoc] PHP function
$res = mysql_query("select email from users where username = '".$_SESSION['username']."'");
$field = mysql_fetch_assoc($res);
echo $field['email'];
You have to fetch the returning rows of your query:
$row = mysql_fetch_assoc($query/$mail);
All the columns you queried will be in the array $row now.
print "Email: " . $row['email'];
This example assumes the query only returned one row.
If you were to query for several rows, you have to call mysql_fetch_assoc each time you wanted a new row:
while($row = mysql_fetch_assoc($query)) {
Good luck.
Take what you need.
$user = strip_tags($_SESSION['username']);
$sql = sprintf("SELECT FROM email WHERE username='%s'", mysql_real_escape_string($user));
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$mail = $row['email'];
echo "Your email is" .$mail;
The strip_tags() method will remove any HTML tags in the submitted entry.
I like to use the sprintf() method when making single row queries because it's a lot faster to just paste and change attribute names then worry about using the correct quote syntax.
Once your query is process you need to fetch the results then you can access the data inside the tables.
I hope this helps you out.
I am kind of stuck since I never tried to get something from the database in this way.
My problem:
I have a single line of code that goes to a website for example src = "www.youtube.com" however that link is stored in a database that has 1 single table called link so i retrieve this link like this
$sql = $db->prepare("SELECT link FROM youtubevid");
I have always used id's but for this table there is no need because it will get updated and i only need that 1 link. My question is how do i echo this?
Help is much appreciated
Thanks!
I guess you are using PDO to do that, if that's the case then you need to execute the query and fetch the result, after the line that you have specified i.e after the.
$sql = $db->prepare("SELECT link FROM youtubevid");
Here is the complete code:
// prepare the query
$sql = $db->prepare("SELECT link FROM youtubevid");
// execute it
$sql->execute();
// fetch the result
$result = $sql->fetch();
// echo out the column.
echo $result['link'];
Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.
I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.
<?php
if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){
echo 'You have successfully logged in.';
echo '<br />';
echo 'These are your tables:';
echo '<br />';
$link = mysql_connect("sql2.njit.edu", "username", "password");
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');
echo $result;
}
else
echo 'You did not provide the proper authentication';
?>
I get no errors. The output is exactly what's echoed, but no table names.
The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.
The only command you actually need is:
show tables;
If you want tables from a specific database, let's say the database "books", then it would be
show tables from books;
You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,
show tables from books like '%book%';
would show you the names of tables that have "book" somewhere in the name.
Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.
Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.
If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
For people that are using PDO statements
$query = $db->prepare('show tables');
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
var_dump($rows);
}
SHOW TABLES
will show all the tables in your db. If you want to filter the names you use LIKE and wildcard %
SHOW TABLES FROM my_database LIKE '%user%'
will give you all tables that's name include 'user', for example
users
user_pictures
mac_users
etc.
The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.
It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
Sure you can query your Database with SHOW TABLES and then loop through all the records but that is extra code lines and work.
PHP has a built in function to list all tables into an array for you :
mysql_list_tables - you can find more information about it at The PHP API page
//list_tables means database all table
$tables = $this->db->list_tables();
foreach ($tables as $table)
{
echo $table;
}
Im a php/mySQL newbie and am trying to get the hang of it. I have code to detect whether i get a username/password match, and now im trying to get the userid field so i can update the record. Heres what I have so far:
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
Using print_r($result) shows that there is an item, but im lost from here on out.
Try this.
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$userID= $row['username'] ;
// If you need other field as userID just change the sql and the index of $row according to that.
}
EDIT
If you want to get only one row.
if($result->num_rows==1)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
$userID = $row["username"];
}
Perhaps this will help. In any programming language, running an SQL query is going to consist of these steps:
Build the text of the SQL statement that you want to run.
(Optional) If your statement involves the use of parameters (or "placeholders"), prepare an array of the parameter-values that are to be substituted for each of them.
("Prepare" and...) "Run" the query, on some previously-opened "database connection." (In your example, "$link" must correspond to that connection.) This gives you a handle (you called it "$result") that corresponds to the zero-or-more rows that were returned by that query.
Now, use that handle to retrieve each of these rows, one at a time, until there are no more or until you're tired of doing it.
(Optional) Be neat and tidy and "close" the handle, thus indicating to the database system that it can discard all of the resources it was using to furnish those rows to you.
"Those, in simple terms, are the basic steps that every program in the known universe are going to go through," and if you now browse again through the PHP documentation, you'll see that there are functions that correspond to each of these steps. Browse through the chapters you've been reading and see if you can now match the up to the scenario I just described. HTH...