I'm having trouble getting any information to display from this query. Anyone know where I'm going wrong?
Thank you!
$query = "SELECT * ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['users.user_id'];
echo $row['comments.comment'];
}
use mysql_fetch_assoc() instead of mysql_fetch_array().
In your loop use the column name as the array key:
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name1'];
echo $row['column_name1'];
}
In your query try to be more specific on the select statement, try not to use *.
You're probably getting the error because you are sorting (ORDER BY) on a field that does not exist in your query.
It would be best practice to not use the "SELECT *" querying. If all you need are specific values, specify them. This also helps when retrieving the data...
$query = "SELECT users.user_id, comments.comment, comments.date ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['user_id'];
echo $row['comment'];
echo $row['date'];
}
It is good practice to specify column names in a query rather than using * - on some DBs there is a performance impact and on all it prevents any unexpected behaviour cropping up from table changes.
In the example I think the issue is arsing from the array keys you are using - you don't need to include the table name in them, just the column name:
echo $row['user_id'];
echo $row['comment'];
The better practice is to write only fields what you need in your sql query like this:
$query = "SELECT u.user_id uid, c.comment comment ".
"FROM comments c, users u ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
Using so type of queries you reduce the time of executing your query and transmitting data from database server to your php script. After this modification your cycle transformed to:
while ($row = mysql_fetch_array($result)) {
echo $row['uid'], $row['comment'];
}
I use PDO method but this can work for you too:
<?php
$sql = "SELECT * FROM comments as c INNER JOIN users as u ON c.user_id=u.user_id WHERE u.user_id=:user_id ORDER BY c.date DESC LIMIT 10";
//prepare the connection to database
$prep = $conn->prepare($sql);
//change the parameters for user_id on WHERE condition you can put anything you want but i will put the user session id
$prep->bindParam(":user_id", $_SESSION['user_id']);
$prep->execute();
//ill use fetchAll function because it can be more than 1 comment
$datas = $prep->fetchAll();
foreach($datas as $data){
echo $data['user_id'];
echo $data['comment'];
echo $data['date'];
}
?>
Related
I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.
I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);
I am VERY new at MySQL and PHP writing. What I am having problems with is pulling data from specific tables, BEFORE the while line. My current code is
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = mysql_query($query_join_tables);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "BLA BLA BLA";
while($row = mysql_fetch_array($result)){
echo "MORE BLA BLA";
The problem is when I attempt to pull from the table BEFORE the while line it won't pull. If I pull after, it works just fine.
Does not work:
echo ".$row['firstname'].";
while($row = mysql_fetch_array($result)){
Does work:
while($row = mysql_fetch_array($result)){
echo ".$row['firstname'].";
Also, before mysqli or PDO are mentioned - I cannot do it. I'm writing a module for something that is encrypted and hard coded.
You will feel silly. The $row variable has not been given the fetched rows yet. when the line
$row = mysql_fetch_array($result)
is run, that is when ONE row's data is given to $row. Calling $row before this point will only give you a null value.
Each time the while loop starts again, it gets a new row. This is called an ITERATOR. It moves down the list one row at a time until it runs and finds nothing. That is when it will exit the loop.
EDIT (01/23/2015): Now that I understand that you actually want to have two loops use the same result. I will show how to reset the iterator.
while($row = mysql_fetch_array($result)) {Do Stuff}
mysql_data_seek($result, 0);
while($row = mysql_fetch_array($result)) {Do Stuff}
Hope this helps.
The mysql extension is deprecated and will be removed in the future. Use mysqli. Try following code.
$con = mysqli_connect("localhost","root","","dbname");
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = $con->query($query_join_tables);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo $row["firstname"];
$conn->close();
Okay, Simply try this. It should work.
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbName");
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = mysql_query($query_join_tables);
$res = mysql_fetch_array($result);
echo $res['vBookName'];
mysql_free_result($result);
Please help me regarding the specified problem:
The code section:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id];'");
// the above query is not working
if ( mysql_num_rows($result) == 0 ) {
print "<p>No events right now.</p>\n";
}
else {
$lasteventmonth = '';
while ($row = mysql_fetch_array($result)) {
$eventmonth="";
$eventmonth = date("F Y",$row['eventdate']);
if ($lasteventmonth != $eventmonth) {
print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
}
$lasteventmonth = $eventmonth;
showEvent($row);
}
}
?>
........................
........................//other codes
when the code evaluates as follows:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Users\Fagun\Desktop\UsbWebserver\Root\mapcal\mapcal.php on line 122
No events right now.++++++++
After your call to mysql_query, use this:
if (! $result) {
echo mysql_errno() . ": " . mysql_error(). "\n";
}
this will tell you exactly, why MySQL won't run your query.
is ID a String or int? Either way I guess you shouldn't include a trailing semicolon?
Try changing it as follows...
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id]'");
I assume it's an issue with how you're using building the query and concatenating the id. Try this instead (notice how the ID is concatenated):
$query = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events
ORDER BY eventdate where
id='".$_GET[id]."'";
$result = mysql_query($query) or die(mysql_error());
You don't have to break it into 2 pieces, but - this should be easier to read and understand. You can even echo out the query before running it to see what query is actually being created, and try it manually on your database.
The or die(mysql_error()) part will give you specifics on what the issue is (if it wasn't the ID issue).
Quote values properly :
$_GET[id] should be $_GET['id']
Try below:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id']."');
Try this:
"SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id'].";'"
I'm assuming that id does not come from user input. If it does, this is vulnerable to a SQL injection attack.
try:
$result = mysql_query("SELECT *,
UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate
FROM events
ORDER BY eventdate
where id= '" . intval($_GET['id']) . "'");
if($result)
{
//Do code
}
use intval() to make sure $_GET['id'] is an integer.
use the if statement to make sure the query has executed correctly.
Try this
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where
id='".$_GET['id']."' ORDER BY eventdate");
I am trying to pull out a row of data from MySQL and put it in an array and then reverse it before displaying the results and then if confirmed by the user it will post the reversed results back into mysql
I am using this code :
for($i=0;$i<6;$i++) {
// Make a MySQL Connection
$query = "SELECT * FROM databasedemo WHERE id='$i'";
$result = mysql_query($query)or die(mysql_error());
$row = mysql_fetch_array($result);
array_reverse($row,true);
echo $i."--"."A".$row['A']. " - ". "B".$row['B']. " - ". "C".$row['C']. " - ". "D".$row['D']. " - ". "E".$row['E'];
echo "<br>";
}
I am getting this error
Warning: array_reverse() [function.array-reverse]: The argument should be an array in /home/nlp4mark/public_html/Databasedemo/main.php on line 37
Any help would be really appreciated. Thanks.
You should only be executing this query once and then iterating through the results and displaying them:
$query = "SELECT * FROM databasedemo ORDER BY id DESC";
$query = "SELECT * FROM databasedemo WHERE id='$i'";
That query will return a one record at the time. You are sending it 6 times with the for loop, that's why you get all the records, but you send 6 times a slighty different query.
try sending one query that return all the 6 records and then reverse it. It would be something like this
$sql = "SELECT * FROM databasedemo WHERE 1=1";
for($i=0;i<6;$i++){
$sql .= " AND id=$i";
}
do like this
select * from (SELECT * from messages INNER JOIN logindata ON messages.author = logindata.id ORDER BY messages.mid DESC LIMIT 0,10) as t ORDER BY t.mid asc