I have a TCP server, which listens for incoming messages(data/requests) and replies accordingly. However, it does not reply after the first connection. If its a data message, the data is inserted into the database, but the confirmation message does not reach the client. And, there is no response if its a data request message. When I restart the server, it replies correctly only to the first incoming connection. Henceforth, there is no response from server to client.
I have attached my code, please suggest what can be done to correct the issue.
/**
* Settings
*/
$listen_address = "0.0.0.0";
$listen_port = ****;
$mysql_server = "localhost";
$mysql_username = "root";
$mysql_password = "*****";
$mysql_database = "*****";
/**
* End Settings
*/
function socketError($errorFunction, $die=false) {
$errMsg = socket_strerror(socket_last_error());
echo("{$errorFunction}() error: $errMsg");
if ($die) {
exit();
}
}
function doQuery($query) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
if (0) echo "Trying query: $query\n";
if(!($res = mysqli_query($db, $query))) {
#mysqli_kill($db, $thread_id);
#mysqli_close($db);
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
if(!($res = mysqli_query($db, $query))) {
echo("Error: " . mysqli_error($db) . "\n");
}
}
return $res;
}
function logMessage($socket, $msg) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
$get_ip = socket_getpeername($socket, $address);
echo("Received ({$address}): {$msg}\n");
// process update:<pid>:<sid>! request
// the response is sent in format: d_id:value<uptill the first comma>,
// in case of multiple rows, they are separated by LF character (\n)
if (preg_match('/^update:([0-9]+):([0-9]+)!/', $msg, $matches)) {
$pid = $matches[1];
$sid = $matches[2];
$res = doQuery("SELECT d_id FROM devices WHERE project_id = $pid AND subproject_id = $sid");
if ($res) {
if (mysqli_num_rows($res) > 0) {
$output = '';
$i = 0;
while ($r = mysqli_fetch_array($res)) {
$res2 = doQuery("SELECT tt.d_id, tt.field_a, tt.value FROM data tt INNER JOIN (SELECT d_id, MAX(update_time) AS MaxDateTime FROM data WHERE d_id = {$r['d_id']} GROUP BY d_id) groupedtt ON tt.d_id = groupedtt.d_id AND tt.update_time = groupedtt.MaxDateTime");
if ($res2) {
if (mysqli_num_rows($res2) > 0) {
while ($r2 = mysqli_fetch_array($res2)) {
$tmp = explode(',', $r2['value'], 2);
$output .= ($i>0?"\n":'').$r2['d_id'].':'.$r2['field_a'].':'.$tmp[0].',';
++$i;
}
}
}
}
return $output;
}
}
}
else {
// Ensure nothing breaks our query
$msg = str_replace("'", "\'", $msg);
$parts = explode(':', $msg);
if (is_numeric($parts[0])) {
//if(!mysqli_query($db, "INSERT INTO data (data, datetime, receiver) VALUES ('{$msg}', '".time()."', '".$address."')")) {
doQuery("INSERT INTO data (sender, d_id, value, update_time, field_a) VALUES ('".$address."', {$parts[0]}, '{$parts[2]}', '".date("Y-m-d H:i:s")."','{$parts[1]}')");
return "yes\n";
}
else return "no\n";
}
}
function sendData($socket, $message) {
socket_write($socket, $message);
}
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
ignore_user_abort(true);
// Stage 1: MySQL Connection
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
else
$thread_id = mysqli_thread_id($db);
// Stage 2: start listening
if(!($server = #socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
socketError("socket_create", true);
}
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(!#socket_bind($server, $listen_address, $listen_port)) {
socketError("socket_bind", true);
}
if(!#socket_listen($server)) {
socketError("socket_listen", true);
}
$allSockets = array($server);
echo("Listening on port {$listen_port}\n");
// Stage 3: accept clients
while (true) {
if(connection_aborted()) {
foreach($allSockets as $socket) {
socket_close($socket);
}
break;
}
$changedSockets = $allSockets;
#socket_select($changedSockets, $write = NULL, $except = NULL, 5);
foreach($changedSockets as $socket) {
if ($socket == $server) {
if(!($client = #socket_accept($server))) {
socketError("socket_accept", false);
} else {
$allSockets[] = $client;
}
} else {
$data = socket_read($socket, 2048);
if ($data === false || $data === '') {
unset($allSockets[array_search($socket, $allSockets)]);
socket_close($socket);
} else {
if(trim($data != "")) {
$response = logMessage($socket, $data);
sendData($socket, $response);
}
}
}
}
}
?>
Related
This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.
I have multiple gps devices. I cannot make changes to this device. It sends data to a port.
I break this incoming data and insert it to the database according to its type. But sometimes I have problems. Device sometimes sends id_number field blank. It sends all other data correctly. And sometimes the program just crashes.
<?php
set_time_limit (0);
$ip_address = "xxx.xxx.xxx.xxx";
$port = "yyy";
$server = stream_socket_server("tcp://$ip_address:$port", $errno, $errorMessage);
if ($server === false) {
die("stream_socket_server error: $errorMessage");
}
$client_sockets = array();
while (true) {
// prepare readable sockets
$read_sockets = $client_sockets;
$read_sockets[] = $server;
// start reading and use a large timeout
if(!stream_select($read_sockets, $write, $except, 300000)) {
die('stream_select error.');
}
// new client
if(in_array($server, $read_sockets)) {
$new_client = stream_socket_accept($server);
if ($new_client) {
//print remote client information, ip and port number
//echo 'new connection: ' . stream_socket_get_name($new_client, true) . "\n";
$client_sockets[] = $new_client;
//echo "total clients: ". count($client_sockets) . "\n";
// $output = "hello new client.\n";
// fwrite($new_client, $output);
}
//delete the server socket from the read sockets
unset($read_sockets[ array_search($server, $read_sockets) ]);
}
// message from existing client
foreach ($read_sockets as $socket) {
$data = fread($socket, 2048);
echo "data: " . $data . "\n";
if($data[0]=='$') {
write_file($data);
$explp = array();
$explp = explode("#",$data);
$i=0;
$j=count($explp);
while ($i < ($j-1)){
$listexa= explode(";",$explp[$i]);
$location= explode(",",$listexa[0]);
$response = "";
$id_number = $location[2];
$package_type = substr($location[0],1);
if ($package_type == 'DATA')
{
$lati = substr($listexa[2],1);
$longi = substr($listexa[3],2);
$speed = $listexa[4];
if(count($speed)>2)
data_package($id_number,$package_no,'DATA');
}
else if($package_type=='GEOLOC')
{
$lati = substr($listexa[3],1);
$longi = substr($listexa[4],2);
$speed = $listexa[5];
if($location[3]=='-' || $location[3]=='2' || $location[3]=='R')
{
$speed= '0';
$package_type = 'GEO';
geo_package($id_number,$package_no,$package_type);
}
}
else if($package_type=='ALIVE')
{
alive_package($package_no,$id_number);
}
$i = $i+1;
}
if (!$data) {
unset($client_sockets[ array_search($socket, $client_sockets) ]);
#fclose($socket);
//echo "client disconnected. total clients: ". count($client_sockets) . "\n";
continue;
}
//send the message back to client
if (sizeof($response) > 0) {
fwrite($socket, $response);
}
}
} }
function alive_package($package_no,$id_number){
$link=dbcon();
try{
$statement = $link->prepare('INSERT INTO alive_packages (package_no, id_number)
VALUES (:package_no, :id_number)');
$statement->execute([
'package_no' => $package_no,
'id_number' => $id_number,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function data_package($id_number,$package_no,$package_type){
$link=dbcon();
$typee= '-';
try{
$statement = $link->prepare('INSERT INTO data_package (id_number, package_no, package_type)
VALUES (:id_number, :package_no, :package_type)');
$statement->execute([
'id_number' => $id_number,
'package_no' => $package_no,
'package_type' => $package_type,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function geo_package($id_number,$package_no,$package_type){
$link=dbcon();
$typee= '-';
try{
$statement = $link->prepare('INSERT INTO geo_package (id_number,package_no,package_type)
VALUES (:id_number, :package_no, :package_type)');
$statement->execute([
'id_number' => $id_number,
'package_no' => $package_no,
'package_type' => $package_type,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function dbcon(){
$dbhost = '127.0.0.1';
$dbname = 'examplename';
$dbusername = 'exampleuser';
$dbpassword = 'examplepassword';
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $link;
}
function write_file($data){
$filename = "xxx.txt";
$file = fopen( $filename, "a+" );
fwrite( $file, $data."\n" );
fclose( $file );
}
function write_file_log($data){
$filename = "yyy.txt";
$file = fopen( $filename, "a+" );
fwrite( $file, $data."\n" );
fclose( $file );
}
I want it to run 24/7 and only restart that socket when something goes wrong. Or I want to take the id_number field of a device once and use it over and over again. Since there are more than one device, a separate socket is opened for each one. But when the id_number of a device is empty, I cannot insert the data to the database. How can I solve this problem?
Briefly, while a socket sends data normally, after a while it starts to send blank id_number and I lose the data until I restart the program. Other devices continue to work.
I have 2 options.
1st option: restart socket when id_number is empty.
2nd option: restart socket when id_number is empty.
But I don't know how to do these.
An additional problem or shortcut is to run the code again when an error occurs in the program. How can I do that?
Note: I am running a php program with a service in Centos 7.
I'm trying to send the result of my MYSQL select query to my Rpi server using PHP through the TCP socket.
Here is the PHP code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "fyp_lora";
$host = "localhost";
$port = 12345;
$f = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($f, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec'
=> 500000));
$s = socket_connect($f, $host, $port);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM led_control";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
echo $row["ID"]. ",". $row["LED"]. "," . $row["Status"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
foreach($data as $value)
{
$msg= $value["ID"]. ",". $value["LED"]. "," . $value["Status"] . "<br>";
$len = strlen($msg);
while (true) {
print($msg);
$sent = socket_write($f, $msg, $len);
if ($sent === false) {
break;
}
// Check if the entire message has been sent
if ($sent < $len) {
// If not send the entire message.
// Get the part of the message that has not yet been sent as message
$msg = substr($msg, $sent);
// Get the length of the not sent part
$len -= $sent;
} else {
socket_close($f);
break;
}
}
}
?>
</body>
</html>
Here is the python code as referenced by:
Sending a message from PHP to Python through a socket
import socket
s = socket.socket()
host = "localhost"
port = 12345
s.bind((host, port))
s.listen(5) #allows for 5 connections to be established
while True:
c, addr = s.accept()
data = c.recv(1024)
if data: print (str(data.decode().split(",")))
c.close() #closes the socket
On the Rpi server, it will only receive the 1st row of the message for example: ['1', 'LED 1', 'OFF'] but it does not receive the rest of the message.
The full message would be as follows:
1,LED 1,OFF
2,LED 2,OFF
3,LED 3,OFF
4,LED 4,ON
I would greatly appreciate any help given :)
The reason only your first line is being received is because you are calling socket_close() after each line is sent in your loop to write data to the socket. This means that the socket is no longer available to socket_write() for subsequent passes of the loop for the remaining lines.
Given that you're just running this on your Raspberry Pi, you could do the following as a quick and dirty fix:
foreach ($data as $value) {
$msg= $value["ID"]. ",". $value["LED"]. "," . $value["Status"] . "\n";
$len = strlen($msg);
$connected = socket_connect($f, $host, $port);
if ($connected) {
while (true) {
$sent = socket_write($f, $msg, $len);
if ($sent === false) {
break;
}
if ($sent < $len) {
$msg = substr($msg, $sent);
$len -= $sent;
} else {
break;
}
}
socket_close($f);
}
}
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
I know how to display data without using class, but i have been asked to use mysql class instead. It seems that i have to initiate the class and just use the written functions, but whatever i try to display - it doesn't work. All i am getting is "Resource id #14", which means that everything should be good with the connection. Please help!
This is a part of the MySQL class:
class SQL //MySQL
{
var $link_id;
var $query_result;
var $num_queries = 0;
function connect($db_host, $db_username, $db_password, $db_name = '', $use_names = '', $pconnect = false, $newlink = true) {
if ($pconnect) $this->link_id = #mysql_pconnect($db_host, $db_username, $db_password);
else $this->link_id = #mysql_connect($db_host, $db_username, $db_password, $newlink);
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
if ($this->link_id){
if($db_name){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
if (!empty($use_names)) $this->query("SET NAMES '$use_names'");
}
} else die(mysql_error());// = "Can't connect to mysql server";
}
function db($db_name) {
if ($this->link_id){
if (#mysql_select_db($db_name, $this->link_id)) return $this->link_id;
else die(mysql_error());// = "Can't open database ('$db_name')";
} else die(mysql_error());// = "Can't connect to database";
}
function query($sql){
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result){
++$this->num_queries;
return $this->query_result;
} else {
$error = "
<pre>
QUERY: \n {$sql} \n\n
ERROR: <span style=\"color:red\">" . mysql_error() . " </span>
</pre>
";
die($error);
}
}
function result($query_id = 0, $row = 0, $field = NULL){
return ($query_id) ? #mysql_result($query_id, $row, $field) : false;
}
function fetch_row($query_id = 0){
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
function fetch_array($query_id = 0){
return ($query_id) ? #mysql_fetch_array($query_id) : false;
}
function fetch_assoc($query_id = 0){
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
function num_rows($query_id = 0){
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
....
and my php code:
<?php
require_once('C:/wamp/www/smarty-3.1.21/libs/Smarty.class.php');
include('C:/wamp/www/smarty-3.1.21/libs/Mysql.class.php');
$smarty = new Smarty();
$smarty->enableSecurity();
$smarty->setTemplateDir('C:\wamp\www\forum\templates');
$smarty->setCompileDir('C:\wamp\www\forum\templates_c');
$smarty->setConfigDir('C:\wamp\www\forum\configs');
$smarty->setCacheDir('C:\wamp\www\forum\cache');
$db = new SQL();
$db->connect('localhost','root','','job', '', false, true);
$db->db('job');
$sql = "SELECT * FROM job";
$db->query($sql);
$output = $db->query_result;
$result = $db->fetch_row();
$smarty->assign('rez', $result);
$smarty->assign('output', $output);
$smarty->display('index.tpl');
?>