I am trying to create a guestbook that shows comments people have posted through an SQL query. I have successfully connected to the SQL database, but the query isn't showing anything. What is wrong here?
</form>
<h2>Current Posts</h2>
";
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
if ($numrows > 0) {
echo "$rows ['email']";
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = $row['message'];
$message = n12br($message);
echo "<div>
$name - and email is $email <hr/>
$message
<div>";
}
}
mysql_close();
?>
</body>
</html>
1) Change
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
To
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
=> Use Backtick instead of single quotes for enclosing table name.
2) You missed $result = mysql_query($sql);
3) You Missed $numrows = mysql_num_rows($result);.
4) Remove echo "$rows ['email']"; line. It's suspense from where it comes.
Mysql (Updated Code)
<?php
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysql_close();
?>
[Note: The mysql_* functions are deprecated, they have been removed from PHP 7, your code will stop working when you upgrade to that version. You should not write new code using them, use mysqli_* or PDO instead.]
Click To Know How can I prevent SQL-injection in PHP?
Mysqli (Updated Code)
<?php
//Connection
$servername = "YOUR-VALUES";
$dbname = "YOUR-VALUES";
$user = "YOUR-VALUES";
$password = "YOUR-VALUES";
$connection = mysqli_connect($servername,$user,$password,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysqli_query($connection,$sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysqli_close($connection);
?>
You are missing a lot of stuff here.
You are closing the PHP tag but not opening it: <?php
You are never actually executing the query, you are missing a call to $result = mysql_query($sql);
You are using $numRows but never actually setting its value: `$numRows = mysql_num_rows($result);
You are using $row = mysql_fetch_row(...) but latter you are reading the resulting row as an associative array instead of a numeric index. You have to use mysql_fetch_assoc instead.
You are never actually connecting to the DB and selecting a schema, I assume you do that somewhere else, but you close the connection at the end. So make sure you are actually connecting.
It seems like you copied this from somewhere else but didn't do it right.
Things that are wrong
The syntax is not within PHP tags so won't do anything
Using single quote marks around a table name is invalid, you need backticks
(or nothing at all)
The $sql statement is never actually run
I assume $numrows is never set, so it will never be over 0
$rows['email'] is not set so it wont echo
$result is never set, so
you won't be able to iterate through it's rows
Original (incorrect) answer
Because you have LIMIT 0, 30. You are telling MySql to give you 0 results starting at index 30.
Also you are using mysql_fetch_row on a query string not a result set, you need to first actually run the query.
-- And indeed i am wrong with my assumption, here is the right thing you need to do:
"; //What is this?
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
$result = mysql_query($sql); //you need to add this
Related
first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>
you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];
Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly
I have a PHP script that queries the database and returns a list of all the usernames in my database. Problem is, it is not printing anything and I think I am doing the while statement incorrectly, this is my code below:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="Ben"{
echo "Here";
}
//$count++;
}
?>
Even something as basic as this doesn't work:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
echo "Here";
//$count++;
}
?>
I can't also seem to increment the count too and it is not even printing the basic "Here"
The main problem is that you are not reading manual/examples properly.
mysqli_stmt_get_result() doesn't change the state of a statement. It returns a mysqli result. So you have to assign this returned value to a variable and than use this one.
Besides, you are using a database completely wrong way. Instead of selecting all rows from database you should always select the only data you need.
For your case the code would be like this.
include "init.php";
$name = "Ben";
$stmt = $dbcon->prepare("SELECT 1 FROM tbl_users WHERE username = ?");
$stmt->bind_param("s", $name);
$stmt->bind_result($found);
$stmt->execute();
$stmt->fetch();
if ($found) ... // here you go
For other cases you have to read the manual or a book carefully. and reproduce the code exactly.
Since there are multiple error in your code i managed to write a code am not sure following is best but it works
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = mysqli_query($sqlconnection, $stmt) or die($mysqli_load->error);
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="ben"){
echo "Here";
}
//$count++;
}
?>
few errors i found in your code are ) is missing here if($row['username']=="Ben"{ next to "ben"){
and use this type of connection
$link = new mysqli("localhost","user","pass","database");
I have inserted couple of emails from a text file into database using mysqli. They get inserted though. Now when I am checking them back I am not getting any result.
Query for inserting emails from text file.
$query = "LOAD DATA LOCAL INFILE 'new.txt' INTO TABLE $table FIELDS TERMINATED BY '\n' (email)";
$result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection),E_USER_ERROR);
Query for checking them back using email not working.
$query = "SELECT email FROM $table WHERE email='email'";
$result = mysqli_query($connection, $query) or trigger_error(mysqli_connect_error(), E_USER_ERROR);
$row = mysqli_fetch_assoc($result);
$email = $row['email'];
echo $email.'<br >';
Query for checking them back using id is working.
$query = "SELECT email FROM $table WHERE id='1'";
$result = mysqli_query($connection, $query) or trigger_error(mysqli_connect_error(), E_USER_ERROR);
$row = mysqli_fetch_assoc($result);
$email = $row['email'];
echo $email.'<br >';
Output of this query shows a white space at the end of email but when I check in database there is no white space.
Please see why this is not working and suggest any possible way to do this.
Thanks
Your code cannot work. mysqli_query returns a mysqli_result object.
You can use mysqli_fetch_array to get the data:
$query = "SELECT email FROM $table WHERE email='email'";
$result = mysqli_query($connection, $query) or trigger_error(mysqli_connect_error(), E_USER_ERROR);
$row = mysqli_fetch_array($result);
$email = $row['email'];
echo $email.'<br >';
By the way: PHP will tell you "undefined variable $row" when you change your error-reporting settings.
Well first of all I am French so I hope my question will be understandable ;-)
I know some people have already experienced problems with queries in php that worked in phpmyadmin. The thing is that each time (or so) these people had "echo" their queries and copy/paste in phpmyadmin, but as php does not always display spaces it was always the problem.
Actually my problem is different :
if I use the query
$sql = "SELECT * FROM jos_dtregister_invoice_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
it returns all the rows in both phpmyadmin and my php code, but if I want to look in a different table (with same structure), it just works in phpmyadmin and not via my php code (only one row instead of all of them)
Here is the query not working:
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
Perhaps the answer is very simple but I admit this is kind of tricky for me...
Many thanks in advance!
Here is my complete code :
function sendReceipt($row) {
$to = getUserInformation($row,10);
$from = getEventAdminEmailFromEmail($row);
$subject = getEventTitle($row)." - Invoice #".$row["confirmNum"];
$message = $row["userFirstName"]." ".$row["userLastName"]." \n\n".getMessageToSendUser($row);
$headers = "From: ".$from."\r\n";
$sql1 = "SELECT * FROM `jos_dtregister_invoice_sent`";
$query1 = mysql_query($sql1);
echo 'Fetched rows number: '.mysql_num_rows($query1)."<br />";
while($row1 = mysql_fetch_array($query1)) {
echo "Invoice Sent: ".$row1["sent"]."<br />";
}
$sql2 = "SELECT * FROM `jos_dtregister_receipt_sent`";
$query2 = mysql_query($sql2);
echo 'Fetched rows number: '.mysql_num_rows($query2)."<br />";
while($row2 = mysql_fetch_array($query2)) {
echo "Receipt Sent: ".$row2["sent"]."<br />";
}
}
mysql_fetch_array() fetches only a row.The name suggests that it fetches a result row as an array
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
Try to execute this. The mysql_error() line will spit out what exactly went wrong when trying to execute the SQL. Post it back here and we can help you a little more.
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
// $row will have your data
}
You need to loop over the results with mysql_fetch_array().
while ($result = mysql_fetch_array($query)) {
print_r($result);
}
Or if you want all your results in one big array ($results):
$results = array();
while ($row = mysql_fetch_array($query)) {
$results[] = $row;
}
I have the code below which is supposed to check the database for entries with a certain username which is working but when I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10 and then if not run another piece of code which will display all the rows.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$checkres = mysql_query("SELECT COUNT link, notes, titles, color FROM links WHERE username='" . $username . "';");
if ($checkres>10)
{
$resultsmall = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10;");
while ($rowsmall = mysql_fetch_array($resultsmall)) { //loop
extract($rowsmall);
$htmlsmall .= "
//code goes here to format results
";
echo $htmlsmall; //display results...
}
}
else {
$result = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "';");
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "
//code goes here to format results
";
echo $html; //display results...
}
}
mysql_close($con); //close db..
But it just displays two times the number of rows in the database instead of either limiting it or displaying them all. How would I fix this? The //code goes here for formatting isn't important it just formats the code so that it looks nice and displays it in a box...
Thanks!
EDIT:
I now have this code but it now doesn't display anything at all? Can someone help:
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if($found_rows > 10)
{
while($row = mysql_fetch_array($result))
{
extract ($row);
$html .= "
//getting values from columns and then formatting them goes here
";
echo "Only 10 is allowed.";
}
}
else
{
while($row = mysql_fetch_array($result))
{
extract($row);
$html .= "
//getting values from columns and then formatting them goes here
";
}
}
mysql_close($con); //close db..
Thanks!
EDIT 2 (12 April 14:03 2011 GMT):
I now have this code which has been kindly helped by Col. Shrapnel but it doesn't display anything for me and I don't know why, please could some help.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT link, notes, titles, color FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql);
if (mysql_num_rows() == 10) {
while ($row = mysql_fetch_array($res)) {
extract($row);
$htmlsmall .= "
=
";
$htmlfree .= "Only 10 is allowed.";
echo $htmlsmall;
echo $htmlfree;
}
}
else {
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= "
";
echo $htmlsmall;
}
}
Now if I view the page source I can see these 2 errors:
<b>Warning</b>: Wrong parameter count for mysql_num_rows() in <b>//url was here</b> on line <b>109</b><br />
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>//url to file goes here</b> on line <b>125</b><br />
Line 109 is this: if (mysql_num_rows() == 10) {
Line 125 is this: while ($row = mysql_fetch_array($res)) {
(Those lines are in the code above)
Please could someone help me with this?
Thanks!
mysql_query() returns either a result statement handle, or boolean FALSE if the query failed. Your outer query is invalid:
SELECT COUNT ...
does not work, so the query fails, returns false, which jumps to the lower "unlimited" query.
However, you're going about the process of limiting things in a roundabout fashion that forces the query to run at least twice.
What you want is
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, etc.... LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if ($found_rows > 10) {
... there's more than 10 rows available, though we're fetching only 10 because of the LIMIT
} else {
... 10 rows or less
}
The SQL_CALC_FOUND_ROWS is a MySQL extension that forces MySQL to calculate how many rows would have been fetched, if the LIMIT clause had not been present. You can get the results of this calculation with the found_rows() query function.
This way, you only run the main query once, do the very very quick found_rows() query, and off you go.
Given that you don't seem to be formatting your output any differently between the "more than 10" and "10 or less" version, except for the "only 10 allowed" line, how about this:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
$rowcount = 0;
while ($row = mysql_fetch_assoc($result)) {
$rowcount++;
... output a row ...
if ($rowcount > 10) {
echo "Only 10 allowed";
break;
}
}
There's no need for duplicated code, excess logic, etc... when something simple will do.
I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10
It makes no sense.
Just run your query with LIMIT 10 and you will get your data.
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= ""; //code goes here to format results
}
echo $htmlsmall;
That's all.
If you still want to echo "Only 10 is allowed." (dunno why though) you can add these 3 lines below
if (mysql_num_rows($res) == 10) {
echo "Only 10 is allowed.";
}
However I see not much point in it.
Also note that your program design is probably wrong, as you're apparently copying this file for the every user in your system
To get number of rows returned in result you must use mysql_num_rows.
if (mysql_num_rows($checkres)>10)