I am using the following script to check a code, so when the user enters the survey code they get the survey that is associated with that code. The part that fetches the survey is working as its supposed to, but I cant seem to get the error message to come up for some reason. If I enter a wrong code or no code all on the form this posts from, all I get is a blank page.
<?php
$con = mysql_connect("myhost","myuser","mypassword;
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Select mysql db
mysql_select_db("mydb", $con);
$questionaireID = $_POST['questionaireID'];
$result = mysql_query("SELECT * FROM itsnb_questionaire WHERE questionaireID='$questionaireID'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if (empty($row['questionaireID'])) {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
} else {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
}
}
?>
It will never get there, because if the resultset is empty, it'll skip the while loop.
Try this, instead, limiting to 1 record (which is what you expect) and using an if...else instead of your while (while is only required when multiple results are expected):
$sql = "SELECT *
FROM itsnb_questionaire
WHERE questionaireID = '{$questionaireID}'
LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if ($row = mysql_fetch_array($result)) {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
} else {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
}
If number of returned rows is zero than you haven't found your result therefore you can display apropriate error message
try
if (mysql_num_rows($result)<1){
//error
}
Related
I have tried a ton of different versions of this code, from tons of different websites. I am entirely confused why this isn't working. Even copy and pasted code wont work. I am fairly new to PHP and MySQL, but have done a decent amount of HTML, CSS, and JS so I am not super new to code in general, but I am still a beginner
Here is what I have. I am trying to fetch data from a database to compare it to user entered data from the last page (essentially a login thing). I haven't even gotten to the comparison part yet because I can't fetch information, all I am getting is a 500 error code in chrome's debug window. I am completely clueless on this because everything I have read says this should be completely fine.
I'm completely worn out from this, it's been frustrating me to no end. Hopefully someone here can help. For the record, it connects just fine, its the minute I try to use the $sql variable that everything falls apart. I'm doing this on Godaddy hosting, if that means anything.
<?php
$servername = "localhost";
$username = "joemama198";
$pass = "Password";
$dbname = "EmployeeTimesheet";
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
$sql = 'SELECT Name FROM Employee List';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["Name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
There be trouble here:
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
There are three problems here:
mysqli_conect() instead of mysqli_connect() (note the double n in connect)
mysqli_connect_errno should be a function: mysqli_connect_errno()
mysqi_connect_error() instead of mysqli_connect_error() (note the l in mysqli)
The reason you're getting a 500 error is that you do not have debugging enabled. Please add the following to the very top of your script:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
That should prevent a not-so-useful 500 error from appearing, and should instead show the actual reason for any other errors.
There might be a problem here:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
If the query fails, $result will be false and you will get an error on the mysqli_num_rows() call. You should add a check between there:
$result = mysqli_query($conn, $sql);
if (!$result) {
die('Query failed because: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
The name of your database table in your select statement has a space in it. If that is intended try:
$sql = 'SELECT Name FROM `Employee List`';
i think you left blank space in your query.
$sql = 'SELECT Name FROM Employee List';
change to
$sql = "SELECT `Name` FROM `EmployeeList`";
I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...
I'm new at PHP, and trying to set up a simple test to get data to return from a temp database I set up, but I keep getting a syntax error. I've looked it over and after the process of elimination, it seems to be in this line, but I'm not sure what's wrong since I'm pretty sure it looks just like the tutorial I'm using.
while($row = mysqli_fetch_row($result)) {
Here is the all the code relevant to what I'm doing:
<?php
// Perform database query
$query = "SELECT * FROM subjects";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die ("Database query failed.");
}
?>
<?php
// Use returned data (if any)
while($row = mysqli_fetch_row($result)) {
// output data from each row
var_dump($row);
echo "<hr />";
?>
I'm able to successfully make the initial connection, etc, it's just when I tried to get data to show up from the database that I got the syntax error.
It's here, you missed your closing braces
<?php
//Use returned data (if any)
while($row = mysqli_fetch_row($result)) {
// output data from each row
var_dump($row);
echo "<hr />";
} //you missed your closing braces
?>
I'm receiving the following error:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource..
and I can't figure out what is going on. Here is my code. I did create a database with a table named notes. Also, the database connection is working correctly. Any idea on what is going on?
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
mysql_fetch_assoc($query)
Thanks
var_dump($query);
echo mysql_error();
Did mysql_query fail and return FALSE? As the documentation explains:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
FALSE would not be a valid resource.
On the PHP page, it gives you a perfect example of how to use it and do error checking...
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
How about you go and implement the entire way making sure rows are returned, and its a valid resource, and if result is truthy?
You should always debug and never assume something executed rightfully.
In the future please read through the entire page of the function on php.net, in this case it's http://php.net/manual/en/function.mysql-fetch-assoc.php
i am trying to do a guestbook in php but i am having some problems with mysql_fetch_array function. I don't understand why. I try to debug by putting
die("Error ".mysql_error()) but nothing prints out. I guarantee that all my variables are correctly initialized.
Here is my code :
<?php
$nbmessagesPP = 10;
mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.......
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$first_msg = ($page - 1) * $nb_of_Page;
$query = 'Select * from livredor ORDER BY id DESC LIMIT '.$first_msg.', '.$nbmessagesPP;
$rep = mysql_query($query) or exit("Error in query".mysql_error());
$v = true;
while($v){
$v = ($data = mysql_fetch_array($rep) or die ("Error fetching the data : ".mysql_error()));
echo "<p>id -> ".$data['id']."</p>";
echo "<p>pseudo ->".$data['pseudo']."</p>";
echo "<p>messages ->".$data['message']."</p>";
echo "<hr/>";
}
mysql_close();
?>
Can someone help me ;)
Your code doesn't deal with errors or the last row correctly. When $v is false, it still goes on to print some data. It would be better rewritten as:
while (($data = mysql_fetch_array($rep))) {
echo
...
}
That forces the evaluation of the fetch before moving on to the printing.
The problem is that you're trying to access elements of the result that don't exist. mysql_fetch_array returns a regular array, with integer indices. What you want is mysql_fetch_assoc, which returns an associative array.
Edit: You also have the problem Chris describes, not dealing with the last row correctly.
Generally, if you're receiving an error saying "supplied argument is not a valid MySQL result resource" it means that your MySQL query has failed, therefor not returning a valid result resource.
Try to echo out $query before sending it through mysql_query(), then try placing the echo'd query into phpMyAdmin and see if it returns any results.
Ok i have found the problem.
The problem was that in another page i had a mysql_connection and in that page i was creating a new one.
I just catch the return value of mysql_connect function and then close it with mysql_close function at the end. Like this :
<?php
$link = mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.....
while($data = mysql_fetch_array($rep)) {//i do something here}
mysql_close($link);
?>
Thanks for your answers folks :)