I'm trying to get a list of values to display upon a selection from a dropdown menu, but I think my SQL is not quite correct. This is a modification of a W3Schools tutorial http://www.w3schools.com/php/php_ajax_database.asp
I get the error: "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/virtual/hafdal.dk/public_html/test/getuser.php on line 28" when I try to do a selection.
I can't seem to find out what the error is, this function should be able to return multiple rows as I want it to. It might be because it's almost 2 am or just cause I'm dense ;-)
See an example here: hafdal.dk/public_html/test/getuser.php
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php header('Content-Type:text/html; charset=UTF-8');
$q=$_GET["q"];
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server) or die("Unable to select database: " . mysql_error());
$sql="SELECT * FROM view_bæjartal WHERE hrepparid = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Bær/Hús/Þurrabúð</th>
<th>Sýsla</th>
<th>Lat</th>
<th>Long</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo utf8_encode("<td>" . $row['bæir'] . "</td>");
echo utf8_encode("<td>" . $row['slysla'] . "</td>");
echo utf8_encode("<td>" . $row['hreppur'] . "</td>");
echo utf8_encode("<td>" . $row['lat'] . "</td>");
echo utf8_encode("<td>" . $row['long'] . "</td>");
echo "</tr>";
}
echo "</table>";
mysql_close($db_server);
?>
<body>
</body>
</html>
I hope someone can help :-)
The reason might that that w3schools tutorial, as usual, forgot the proper escaping function. This might lead to a syntax error, and due to the absence of any error checking code a failure with the loop.
Right after your mysql_query() add a mysql_error() call:
$result = mysql_query($sql) or print(mysql_error());
It could also just be your Unicode table name. (Then add backticks.)
You can display errors by calling echo mysql_error($db_server); right after your queried the database (with mysql_query($sql)).
Maybe there is a problem with your table/view name, but to know this for sure you need to have a look at the actual error message returned by mysql.
Related
im trying to create my first website and Im clueless in this case.
So I have a MySQL-Database with a table. And I have a php-File called database.php which reads from the database and echos all the lines of a query:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now on my index.php I want to execute this php-code on calling/loading the webpage and print all the lines (data entries).
But i have no idea how to get the echo (=data entries) of the php file printed in the body of my webpage. I read about AJAX and using a js-script but I still wasnt able to figure it out.
Thanks for your help.
Option 1: Place your PHP code inside the HTML body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
Option 2: Create a separate PHP file containing your code above and include/require it into your body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
Option 3: Call your PHP file using an AJAX call (e.g. by using jQuery load()).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
If your index file is index.php then the PHP code will be run when you load the webpage. That is assuming, of course, that your web server (local or remote) has PHP installed.
I keep getting the following error:
Fatal error: Call to a member function fetch_array() on boolean in C:\xampp\htdocs\DeletePlayerSOLN\DeletePlayerExample_SOLN\index.php on line 10
Any idea what the problem is? I searched previous threads and tried to identify the problem for the past few hours. I'm new to PHP.
I'm using Xampp + Mysql.
MySQL connection:
127.0.0.1
3306
root
Default Schema: test
I'm connected through port 443,4433 through Xampp. So I try to connect through /localhost:443/folder..filename..
Connection:
//make a database connection object
$mysqli = new mysqli($server, $user, $pass, $database);
//test if there are database connection errors
if ($mysqli->connect_error)
die("Connect Error " . $mysqli->connect_error);
?>
Index page:
<?php
require "serverCode/connect.php";
$selectPlayer = "SELECT * FROM player ORDER BY playerLastName, playerFirstName";
$results = $mysqli->query($selectPlayer);
$ddlString = "<select name='cboPlayer' size='10'>";
while($row = $results->fetch_array())
{
$ID = $row["playerID"];
$name = $row["playerLastName"] . ", " . $row["playerFirstName"];
$ddlString .= "<option value='$ID'>$name</option>";
}
$ddlString .= "</select>";
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DELETE Player Page</title>
</head>
<body>
<form name="frmPlayer" action="serverCode/deletePlayer.php" method="get">
Select a player:<p><?php echo $ddlString;?>
<input type="submit" name="btnSubmit"></p>
</form>
</body>
</html>
Line 10 is "while($row = $results->fetch_array())"
It is likely that $mysqli->query() is not producing a proper object due to an error. Try replacing
$results = $mysqli->query($selectPlayer);
with
$results = $mysqli->query($selectPlayer) or trigger_error($mysqli->error."[$selectPlayer]");
I have the following code that allows me to upload a file to a database but I have cannot get that file to playback on my html page:
<!DOCTYPE html>
<html>
<head>
<link href="site.css" rel="stylesheet">
<title>A</title>
<meta http-equiv="content-type" content="text-html; charset=utf-8">
</head>
<body style="background-color:black">
<?php
define('DB_Name', 'gaufensr_abs3x');
define('DB_User', 'gaufensr_owner');
define('DB_Password', 'Mlee#0407');
define('DB_Host', 'localhost');
$link = mysql_connect(DB_Host, DB_User, DB_Password);
if (!$link) {
die('could not connect:' . mysql_error());
}
$db_selected = mysql_select_db(DB_Name, $link);
if (!#db_selected) {
die('can\t use' . DB_Name. ': ' . mysql_error());
}
echo 'CONNECTED SUCCESSFULLY';
$value = $_Post['submit'];
$sql = "INSERT INTO videos (video_name) VALUES ('$value')";
if (!mysql_query($sql)) {
die('ERROR: ' .mysql_error());
}
mysql_close();
?>
<?php
if (isset($_GET['id']))
{
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM 'videos' WHERE id='$id'");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$video_name = $row['video_name'];
}
echo "You are watching " .$video_name. "<br />";
echo "<embed src='$id' width='560' height='315'></embed>";
}
else
{
echo "Error!";
}
?>
</body>
</html>
When i upload a file I get the following error:CONNECTED SUCCESSFULLY Error!
I am just learning php and mysql; Any help would be great. Thanks in advance you guys.
Firstly, you're using the incorrect identifiers for your table, being regular single quotes.
FROM 'videos'
Those should be ticks or none at all.
FROM `videos`
Having used or die(mysql_error()) to mysql_query() would have signaled the syntax error.
Sidenote: Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Then this $_Post that should be in uppercase $_POST is a superglobal.
http://php.net/manual/en/language.variables.superglobals.php
Plus, you are closing your DB connection too early with mysql_close(); where you have it placed now.
Place it after your queries, at the end of your code. That could have adverse effects.
Your conditional statement if (isset($_GET['id'])){...} could also play a part in all this.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I am trying to make a connection to SQLite using PHP.(I am basically trying to browse through the database of Spiceworks which is on my system.)
My PHP code works fine till sqlite_open. But it does not proceed beyond SQLITE_OPEN.
What could the problem be? How do I correct it?
My code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php
// set path of database file
echo "Hello!";
$db = "C:\Program Files (x86)\Spiceworks\db\spiceworks_prod.db";
// open database file
$handle = sqlite_open($db) or die("Could not open database");
// generate query string
$query = "SELECT * FROM devices";
// execute query
$result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));
// if rows exist
if (sqlite_num_rows($result) > 0) {
// get each row as an array
// print values
echo "<table cellpadding=10 border=1>";
while($row = sqlite_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
// all done
// close database file
sqlite_close($handle);
?>
</body>
</html>
It could be because the route of the database, why don't you try to use $_SERVER['DOCUMENT_ROOT'] or something similar and take this as your path to the database?
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm new to PHP, and I tried to research this question but maybe I'm not asking right... I can tell from other posts/instructionals that I can not user header() or setcookie() after printing out HTML...
I commented out the header "redirects" - is there an alternative to this that I can put after HTML?
It's the setcookies that are failing at the moment:
what am I not seeing? I keep getting errors but my HTML is after the PHP:
if (!isset($_COOKIE["user"])) {
$sUserIdentity = $_POST["userIdentity"];
//username is not accepted as a get value
$sPassword = $_POST["password"];
$sEmail = $_POST["email"];
$cnn= odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
//check to see if email account or username already used
$sql2 = "select id from i_user where email = '" . $sEmail . "' or username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$id = odbc_result($result,"id");
if ($id == ''){
$cnnCreate = odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
$sqlCreate = "insert into i_user (username,email,salt,active) values ";
$sqlCreate .= "(";
$sqlCreate .= "'" . $sUserIdentity . "',";
$sqlCreate .= "'" . $sEmail . "',";
$rsCreate = odbc_exec($cnnCreate, $sqlCreate);
$sql2 = "select * from i_user where email = '" . $sEmail . "' and username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$expire=time()+60*60*24*30;
setcookie("uid", odbc_result($result,"id"), $expire);
setcookie("user", odbc_result($result,"username"), $expire);
if ($rsCreate){
$sMsg = "congratulations " . $_COOKIE["user"] . " and welcome ";
}
else {
$sMsg = "There was an error with the query";
}
}else{
$sMsg = "User " . $id . " already in DB";
//header('Location: ../fec/createuser.php?error=id');
}
}
//echo $sqlCreate;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Form</title>
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.2.custom.min.js"></script>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<style>
</style>
</head>
<body>
</body>
</html>
Make sure <?php is at the very beginning of the file, with no blank lines before it. And you can't print or echo anything before calling setcookie().
Why don't you use output buffering?
<?php
ob_start();
?>
<html>
<body>
...
</body>
</html>
<?php
ob_end_flush();
?>
This will put any output into a buffer and you can modify header information as long as the buffer isn't flushed.
This will also avoid problems in case a PHP warning or error message was sent to output before you write to the header.