SQLite and Spiceworks - php

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?

Related

Show Output/Echo of PHP File executing at load on webpage

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.

Save text with Tinymce online editor in Mysql database and show the saved text on the website

I have another question about connecting to Mysql database.
I have a simple text document with Tinymce online text editor. Online I want to change the text with the editor, save it to Mysql database and then show the new text online. I have the following scripts and I get this error from the file doAddContents.php:
Warning: mysql_real_escape_string(): Access denied for user ''#'localhost' (using password: NO) in /../doAddContents.php on line 8
Warning: mysql_real_escape_string(): A link to the server could not be established in /../doAddContents.php on line 8
I have no idea what I'm doing wrong. Here are the scripts:
first the script to connect to the database:
db.php:
<?php
function doDB() {
global $mysqli;
//connect to server and select database
$mysqli = mysqli_connect("localhost", "name", "pass", "db-name");
//if the connection fails, stop script execution
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
?>
doAddContents.php file:
<?php
include("db.php");
doDB();
$h4_block = "Contents Saved!";
$elm1 = $_POST['elm1'];
$entity_elm1 = htmlentities($elm1);
$entity_elm1 = mysql_real_escape_string($entity_elm1);
$add_contents_sql = "UPDATE tinymce_contents SET `contents`=
'$entity_elm1', `modified`=now()";
$add_contents_res = mysqli_query($mysqli, $add_contents_sql)
or die(mysqli_error($mysqli));
//close connection to MySQL
mysqli_close($mysqli);
//create nice message for user
$display_block = "<p>The page has been successfully updated.</p>";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $display_block; ?>
View Page!
</div>
</body>
</html>
View.php file:
<?php
include("db.php");
doDB();
$h4_block = "View Page!";
$get_contents_sql = "SELECT * FROM tinymce_contents";
$get_contents_res = mysqli_query($mysqli, $get_contents_sql)
or die(mysqli_error($mysqli));
if ($get_contents_res = mysqli_query($mysqli, $get_contents_sql)) {
//fetch associative array
while ($row = mysqli_fetch_assoc($get_contents_res)) {
$id = $row['id'];
$contents = $row['contents'];
$modified = $row['modified'];
//Draw the results
$view_block ="<p>ID: ".$id."</p>";
$view_block .="<b>Contents</b>:".html_entity_decode($contents);
$view_block .="<b>Modified</b>:".$modified."<br/>";
}
}
//close connection to MySQL
mysqli_close($mysqli);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $view_block; ?>
Back to Page Edit!
</div>
</body>
</html>
According to the documentation of mysql_real_escape_string. The function will try to create a mysql connection if there is no connection opened with mysql_connect().
http://php.net/manual/en/function.mysql-real-escape-string.php
You should not be using mysql_real_escape_string() but mysqli_real_escape_string()
http://php.net/manual/en/mysqli.real-escape-string.php

MySQLi mysqli fech array assoc replacement NO working

here is what I want but cannot make it work with the new MySQLi just because my host does not have all new php etc...
But there must be some kind of solution or thats all MYSQLI can do ?
Please dont talk about PDO because even the ugly name sounds like PEDO and I am only interested in MySQLI and a solution for this simple thing. Please dont change the structure of my script. The question is only is if there is something to make it work with MySQL or if I maybe switch back to MySQL procedure instead of statements
<?php
$sql = new mysqli('localhost','user','pass','db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s",$who);
$result = $query->execute();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // << HERE IS THE PROBLEM //
// I GET ERROR Fatal error: Call to a member function fetch_array() on a non-object in ... //
"" but there must be some way to make it work like we do with while($row = mysqli_fetch_array($sql)) //
{
?>
<!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>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo "$row[USERNAME]"; ?>
YOUR INFO IS <?php echo "$row[JUST_SOME_INFO]"; ?>
</body>
</html>
<?php
}
?>
Here is your solution
You don't have to use fetch_array() but use fetch()
also you will have to bind result using bind_result before fetch
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
You can use $col1 directly also, no need to use it with printf()
My working example according to my db is given below if you want more assistance,
$sql = new mysqli('localhost','user','pass','dbname');
$who = 'php';
$query = $sql->prepare("SELECT * FROM job WHERE skill=?");
$query->bind_param("s",$who);
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
Comment this string:
$result = $query->get_result();
you don't need this.
Try this one.
<?php
$sql = new mysqli('localhost', 'user', 'pass', 'db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s", $who);
$result = $query->execute() or die($query->error);
while ($row = $result->fetch_array()) {
$username = $row[USERNAME];
$info = $row[JUST_SOME_INFO];
}
?>
<!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>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo $username; ?>
YOUR INFO IS <?php echo $info; ?>
</body>
</html>
This is what happens when you start copying and pasting php together without knowing what it means.
the solution here is:
create a class for $sql or declare $sql a global imediately after calling the variable.
try
global $sql;
but if you actually want to fix the problem(by making your $sql variable an object)
try
$sql = array();
$sql['host'] = 'host';
$sql['user'] = 'user';
$sql['pass'] = 'password';
$sql['db'] = 'database';
global $sql;
$db = new mysqli($sql);
Now when you wanna do something with the db connection.
$db->action();
this is just the basics and probably won't work. you probably should instead read more on php/mysqli before attempting to write your own classes.

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

mysql_fetch_array(): error message

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.

Categories