I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.
Related
i am trying to print the results of a php query my php code is:
<?php
include 'header.php';
include 'conect.php';
$resultlog = mysqli_query("SELECT * from cpi ,$con);
while($row = mysql_fetch_array($resultlog))
print $row;
mysqli_close($con);
?>
but it result an error
Parse error: syntax error, unexpected end of file
Firstly, the DB connection comes first in mysqli plus, there's a missing quote.
You're also mixing APIs.
Then add the proper bracing.
$resultlog = mysqli_query($con,"SELECT * from cpi") or die(mysqli_error($con));
while($row = mysqli_fetch_array($resultlog)){
print $row;
}
mysqli_close($con);
Make sure your DB connection which is not shown, is in fact mysqli and not mysql, nor PDO.
None of those APIs intermix.
However, just doing a print $row may probably not show you what you like to get.
Therefore, you may need to elaborate on that.
You're probably wanting to do something like:
echo $row['your_column_name'].'<br />';
or as Ghost stated:
print $row[0]; or print $row['column_name']
"Its working fine. But can we print all result through one command?"
Yes, like this:
$resultlog = mysqli_query($con,"SELECT * from cpi") or die(mysqli_error($con));
$row = mysqli_fetch_array($resultlog);
foreach($row as $r) {
echo $r . "<br>";
}
try this:
<?php
include 'header.php';
include 'conect.php';
$resultArray = array();
$resultlog = mysqli_query($con, "SELECT * from cpi");
while($row = mysqli_fetch_array($resultlog)){
$resultArray[] = $row;
}
mysqli_close($con);
print_r($resultArray);
?>
before you send me thousand of links to the problem of other please read my code. i googled my problem for about an hour and tried every suggestion i could find. I got a similar code example from php book but its not working on my local server.
my code:
$mysqli = new mysqli("localhost", "root", "", "poi_site");
if ($mysqli->connect_error){
echo "something went wrong!".mysqli_connect_error();
exit();
}
echo "db connection is stable";
$mysqli->close();
$result = $mysqli->query("SELECT name FROM cities;");
while($row = $result->fetch_array()) {
echo " {$row['name']}";
}
$result->close();
i already tried to get a error output and that showed me that "result" is null, like i expexted the problem from the other people.
my errors at the moment are:
Warning: mysqli::query(): Couldn't fetch mysqli in ...
Fatal error: Call to a member function fetch_array() on a non-object in ...
dont know how to solve the problem. thanks
EDIT: sorry i had a typo in the code here, it was right on my code!
A wrong ";" after cities in here:
$result = $mysqli->query("SELECT name FROM cities;");
$result = $mysqli->query("SELECT name FROM cities");
This has to be $result instead of $ergebnis
while($row = $ergebnis->fetch_array()) {
while($row = $result->fetch_array()) {
U don't need "{" and "}" after and before the $row statement here:
echo " $row['name']";
echo " $row['name']";
Your closing the database, before the query here:
echo "db connection is stable";
$mysqli->close();
Delete this line!
Try to change this code
$result = $mysqli->query("SELECT name FROM cities;");
while($row = $ergebnis->fetch_array()) {
echo " {$row['name']}";
}
with this one and check if also you haven't result
$result = $mysqli_query($conn,"SELECT name FROM cities");
while($row = mysqli_fetch_array($result)) {
echo " {$row['name']}";
}
while($row = $ergebnis->fetch_array()) {
to
while($row = $result->fetch_array()) {
check the very first example here
http://us2.php.net/manual/en/mysqli-result.fetch-array.php
UPDATE :
$mysqli->close();
is done prior to fetch so this should be the last line of your code after u have done with all the operations are done.
I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.
I am learning PHP and MySQL from 'PHP and MySQL web dev'. Currently I am finding difficulties in displaying results from database. Here is the code:
<body>
<?php
$searchtype = $_POST['searchtype'];
$seachterm = trim($_POST['searchterm']);
if(!$searchtype || !$seachterm){
echo "You did not enter all the details. Bye";
exit;
}
if(!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$seachterm = addslashes($seachterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if(mysqli_connect_errno()){
echo "Sorry Could not connect to db";
exit;
}
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
$result = $db -> query($query);
$num_of_results = $result->num_rows; // Line 47
echo "Num of books found is ".$num_of_results." ";
for($i = 0; $i < $num_of_results; $i++){
$row = $result -> fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db -> close();
?>
</body>
When I run the above code, this is the error i get.
Notice: Trying to get property of non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 47
Num of books found is
Fatal error: Call to a member function free() on a non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 64
What am I doing wrong?
There's probably an error in your SQL query and $result is false instead of the result object.
I think it's probably because you're missing some spaces in the query. This line:
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
should be something like:
$query = "SELECT * FROM books WHERE '" .$searchtype. "' LIKE '%".$seachterm."%'";
It would help if we knew the values of:
$_POST['searchtype'];
$_POST['searchterm'];
You're not checking to make sure that $result is what you think it is. It's very likely that something went wrong with your query, and the return value of $db->query() is false. It's a good idea to check for that to make sure your query actually worked.
Try using this code:
$result = $db->query($query);
if ($result === false) {
// Query failed - we can't continue
die('My query failed, I want to be a teapot instead.');
}
// Now it's safe to operate on $result, deal with a successful query, but no results
if ($result->num_rows == 0) {
echo 'no results found.';
// display any other output, search again?
exit;
}
// At this point you have results to display
Now, as to why your query is failing, take a look at this part closely:
"select * from books where".$searchtype."like '%"
You need some spaces. If $searchtype was 'foo', your query would actually expand to:
select * from books wherefoolike
Try instead:
"select * from books where ".$searchtype." like '%"
Notice the space after 'where' and before 'like'? That should probably fix it.
I'm not going to harp too much about making sure your query is properly prepared for safety, your book should go into that - but do keep it in mind.
I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .