My table in the database contains 3 columns that all has qwe for a username and have the respective dates of January, February and March but when I try to echo them it only displays January. I'm trying to get them all into a drop down list but I can't get past this so I have to make sure I get all of these dates before I put them elsewhere.
{
$con=mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request="SELECT date FROM mytable WHERE username='qwe'";
$result=mysqli_query($con, $request);
$fetch=mysqli_fetch_assoc($result);
echo $fetch['date']; echo "<br>";
print_r($fetch);
}
You are missing loop, data come up. You can see when you are printing data using print_r($fetch), use loop to show one by one.
And also try to don't use user input directly in query before checking mysql injection. like you have putted username='qwe' if username is user input then use it like this directly in query Suggestion for query
$request = "SELECT date FROM mytable WHERE username=".mysql_real_escape_string('qwe');
and your with loop try this,
$con = mysqli_connect('localhost', 'root', '') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request = "SELECT date FROM mytable WHERE username='qwe'";
$result = mysqli_query($con, $request);
print_r($fetch);
while ($fetch = mysqli_fetch_assoc($result)) {
echo $fetch['date'];
echo "<br>";
}
?>
Related
I have something that may seem very simple for some people but for the life of me I cannot figure it out (and I've been trying all day long). I have simple DB from which I am trying to get SUM by the client by date. All works fine to the last moment where I add SUM(item) to SELECT - from this point I cannot echo anything. Can anyone help me what is wrong with my code below:
<?php
$q_billing = intval($_GET['q_billing']);
$dblink = mysqli_connect("localhost", "User", "Pass", "Exam_2018");
/* If connection fails throw an error */
if (mysqli_connect_errno()) {
echo "Could not connect to database: Error: ".mysqli_connect_error();
exit();
}
$sqlquery = "SELECT id, client_id, SUM(item) AS total_sales, date
FROM test
WHERE date BETWEEN '".$q_billing."' AND '2018-12-31'
GROUP BY client_id ";
if ($result = mysqli_query($dblink, $sqlquery)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo $row["client_id"]." ".$row['total_sales']."<br />";
}
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close
?>
Just a note that q_billing is DATE, which I tried to replace with constant 2018-01-01.
I tried also adding ORDER BY, but it does not make any difference. I cannot see any error either - just a blank div where the echo should be.
Thank you for any help
if you group by client_id then you should not select id and date
$sqlquery = "SELECT client_id, SUM(item) AS total_sales
FROM test
WHERE date BETWEEN '".$q_billing."' AND '2018-12-31'
GROUP BY client_id ";
I've just started learning PHP so this is quite a struggle for me, any help is appreciated!
So, I've managed to select my database, table and get data from it. But I need to select more data from the older columns.
Here is some of the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//execute the SQL query and return records
$result = mysqli_query($conn, "SELECT username FROM interview");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$username2= $rowval['username'];
$username3= $rowval['username'];
$username4= $rowval['username'];
}
?>
And I am displaying the data in a button, I want $username to display the first column and $username2 to display the second column etc...
I fetch the data using this code:
<?php echo $username; ?>
<?php echo $username2; ?>
<?php echo $username3; ?>
<?php echo $username4; ?>
Thanks!
I would suggest you re-factoring your "while" loop the following way for better scalability:
$usernames=array();
while($rowval = mysqli_fetch_array($result))
{
$usernames[] = $rowval['username'];
}
Then, you'll be able to access usernames like:
echo 'The first user name is: '.$usernames[0];
echo 'The second user name is: '.$usernames[1];
echo 'The third user name is: '.$usernames[2];
My php skills are a bit rusty, so take this with a grain of salt:
At first it is important to get the language right. A database table consists of rows and columns, the columns are the ones you select with the the part after the SELECT statement, if you write SELECT username what you select is the username column.
SELECT username FROM interview;
So if you want to select more columns from your table you have to put them in your SELECT statement. Let's say you want to select the username and the status of the interview, you would need to include the status in your SELECT statement like this:
SELECT username, status from interview;
Then you can access the interview status just like you did it with the username.
$result = mysqli_query($conn, "SELECT username, status from interview;");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$status = $rowval['status'];
}
Remember that what you get as the $rowVal is just a single row of your table. So if you want to collect all usernames and statuses from your table you have to use a datastructure to collect them.
$queryResult = mysqli_query($conn, "SELECT username, status from interview;");
$result = array();
while($rowval = mysqli_fetch_array($queryResult))
{
$username= $rowval['username'];
$status = $rowval['status'];
// With this action we build an array, that has each row's result as value.
$result[] = array('username' => $username, 'status' => $status);
}
To access the results you can then query the $result array like this:
// The interview status of the first entry in your table
$result[0]['status'];
I have uploaded a PHP script in the server. What it does is, that it keeps reading the DB (mySQL), and if the DATE_OF_MATCH and TIME_OF_MATCH (these are 2 fields in the mySQL db) is equal to the server time it will execute a message.
fields in the table: all are VARCHAR
ID, DATE_OF_MATCH, TIME_OF_MATCH, MATCH_NAME
One record from the MATCH table;
1 , 1/12/2012, 3:40, ManU vs Kaks
The problem is that, my select statement is wrong. My $theDateAndTime is returning 09:15:03PM and in the Database i am having 2 separate records for date and time. So how can i edit the select statement so could match the date and time against the $theDateAndTime (returned by the server)
The code:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
date_default_timezone_set('America/New_York');
$theDateAndTime = date("h:i:sA")."\n";
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$theDateAndTime." and TIME_OF_MATCH=".$theDateAndTime."");
while(true){
if(result!=null){
while($row = mysql_fetch_array($result))
{
echo $row['MATCH_NAME'] ;
echo "<br />";
}
}
}
mysql_close($con);
?>
I don't understand your question very well, but seems that you are trying to query for date and time in two different fields but you are only take the current time. I think you should try something like this:
<?php
$current_date = date('d/m/Y');
$current_time = date('h:i');
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$current_date." and TIME_OF_MATCH=".$current_time."");
Otherwise, you should not use mysql_* functions, use mysqli_* functions instead with prepared statements.
Create two separate variables for date and then time.
$the_date = date("n/j/Y");
$the_time = date("h:i:s");
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH={$the_date} and TIME_OF_MATCH={$the_time}");
http://us3.php.net/manual/en/function.date.php
I want to display some basic data from a MySQL database. Here's the current code I have, but it doesn't seem to work. Could someone please explain why this doesn't work and offer a solution? Thanks!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM 'users' ORDER BY 'DATE' DESC LIMIT 8';
echo = "'$result'"
?>
Providing your connection and structure information is correct, the following should work for you:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$query = mysql_query($result) or die("Query Error");
while($row = mysql_fetch_assoc($query))
{
echo = "'" . $row['user'] . "'";
}
?>
You forgot to query the database!
You need to use mysql_query() to retrieve data from your DB server, then loop through it with a while() loop.
Also, you can't use quotes inside quoted strings - it breaks the string, meaning you'll get a syntax error with the SELECT ... line. You don't actually need to quote database fields in queries, so the following should work fine:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM users ORDER BY DATE DESC LIMIT 8';
$result = mysql_query($query); // Query the database.
// Loop through each returned row
while($row = mysql_fetch_assoc($result))
{
print_r($row); // Prints the current row
}
?>
To show any errors that PHP reports, put these two lines at the top of your script.
error_reporting(E_ALL);
ini_set('display_errors', '1');
They will output any errors you get, making problems much easier to solve.
After the selecting the database need
$stmt = mysql_query("SELECT * FROM users ORDER BY DATE DESC LIMIT 8");
while ($result = mysql_fetch_array($stmt, MYSQL_NUM))
{
var_dump($result);
}
mysql_free_result($stmt);
You should query your string and then echo the result, like this for example:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$result = mysql_query($query);
echo = "'$result'"; // This may need a foreach loop
?>
You should escape the ' in your string, because you use them to open and close your string too. The syntax highlighter actually tells you that you are wrong ('users' and 'DATE' are black instead of maroon). :)
Please see the PHP.net documentation about strings:
After that, you'll need to further process $result. It is just a resource pointer and cannot be echoed that way. But that's a second step. :)
I have this code in PHP
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
then the output be:
The max num is this is it
hh
Why didn't the query get the max number?
The table is called info and it has these fields, ID, num, title, description, and answer.
After editing:
I tried my query in MySQL and it works fine!
"SELECT MAX(num) FROM info"
and this is my complete code if it can help:
<?php
$answer=$_GET["answerbox"];
$ID=$_GET["TheID"];
$host="localhost";
$username="root";
$password="";
$db_name="game";
mysql_connect("$host","$username","$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
$sql="SELECT * FROM info WHERE ID=".$ID;
$query = mysql_query($sql) or die(errorquery);
$row = mysql_fetch_array($query);
$trueanswer = $row['Answer'];
$num=$row['num'];
if ($num<$maxnum)
{
$numto= $num +1 ;
echo "<br>".$maxnum."hh";
}
?>
Then the code will be
$max="SELECT MAX(num) as num FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_assoc($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
The column you are looking for in the result set is NOT called num. Try print_r($row); to see what the array indices are, or give it an alias, e.g.
$max="SELECT MAX(num) AS max_num FROM info";
...
echo "The max num is ". $row['max_num']
Here is another and simpler way:
$query="SELECT MAX(num) FROM info";
list ($max) = mysql_fetch_row(mysql_query($query));
print ($max);
num field in your database has to be a numeric datatype (i.e. int, float etc) in order for this to work properly.
It's because your query returns a scalar value, not an array. $maxquery is the value you want to get.
I recommend checking your query against the database before try running it with PHP.
Run your query within the MySQL query window then analyse the output. That way you can concentrate on the query without the PHP getting in the way.
Once you've done that modify the question so that we can see the query that's actually being run.
The query is looking fine. Please inspect your code of getting data from the result set step by step.