jQuery Autocomplete get feeds from mysql DB - php

Do you have an idea how to pull data from mysql, put it in an array then feed it in an autocomplete field?
I have tried hardcoded the values but what I'm thinking is when I add a new record, I have to re-code again the array. I'm a newbie in PHP so I beg your pardon.
Kindly check what I've tried so far:
protected function jsGenerateResourcesAutocomplete(){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT employee_name FROM employee" ;
mysql_select_db('test', $conn);
$retval = mysql_query($sql);
$row = mysql_fetch_assoc($retval);
if(!$retval )
{
die('Could not select data: ' . mysql_error());
}
$employeeNames = $this->employeeNames;
$html = ""; $html .= 'var employeenames = [' . PHP_EOL;
foreach ($employeeNames as $employeeName) {
$html .= '"' . $employeeName-> $array . '",' . PHP_EOL;
}
$html .= '];';
$html .= '$(".resource-input input").autocomplete({source: employeenames});' .PHP_EOL;
$html .= '});' . PHP_EOL;
$html .= '</script>' . PHP_EOL;
return $html;
}
I believe something in this line:
$html .= '"' . $employeeName-> $array . '",' . PHP_EOL;
I have to put forth the array but I have no idea how to do it. Any help is truly appreciated. Thanks.

Try this way:
$sql = "SELECT employee_name FROM employee" ;
mysql_select_db('test', $conn);
$retval = mysql_query($sql);
if(!$retval )
{
die('Could not select data: ' . mysql_error());
}
$data = array();
while($row = mysql_fetch_array($retval)){
$data[] = $row['employee_name'];
}
$html = "<script>";
$html .= 'var employeenames = '.json_encode($data);
$html .= '$(".resource-input input").autocomplete({source: employeenames});';
$html .= '});';
$html .= '</script>';
return $html;

Related

how to take backup of mysql database using php

I need to export backup of the database using php when I click on the link. I searched so many references and created code. But when I execute this it displays error. Can anyone help me to get the solution? This is my code
BACKUP
Back.php
<?php
include('../database.php');
$dbhost = $_SERVER['SERVER_NAME'];
$dbuser = 'root';
$dbpass = '';
$dbname='marketing';
$backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass ". "$dbname | gzip > $backup_file";
$sys=system($command);
if($sys)
{
echo "succc";
}
else{
echo "failed";
}
?>
You may use the following code pattern directly with your task
<?php
$dbhost = $_SERVER['SERVER_NAME'];
$dbuser = 'root';
$dbpass = '';
$dbname = 'marketing';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$backupAlert = '';
$tables = array();
$result = mysqli_query($connection, "SHOW TABLES");
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($connection, "SELECT * FROM " . $table);
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$num_fields = mysqli_num_fields($result);
if (!$num_fields) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= 'DROP TABLE ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
if (!$row2) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$backup_file = $dbname . date("Y-m-d-H-i-s") . '.sql';
$handle = fopen("{$backup_file}", 'w+');
fwrite($handle, $return);
fclose($handle);
$backupAlert = 'Succesfully got the backup!';
}
}
}
}
echo $backupAlert;
?>
I use this Script as sheduled CRON task.
// Edit this section
$dbhost = "SERVER IP OR LOCALHOST";
$dbuser = "DB USER";
$dbpass = "DB PASSWORD";
$dbname = "DB NAME ";
$message = "E-MAIL MESSAGE TEXT";
// Don't need to edit below this section
function compress($filepath) {
$zip = new ZipArchive();
$file=$filepath.".zip";
if($zip->open($file,1?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE) {
// Add the files to the .zip file
$zip->addFile($filepath);
// Closing the zip file
$zip->close();
}
}
ini_set('date.timezone', 'Europe/Budapest');
$backupfile = $dbname.'_'.date("Y-m-d_H-i", time()).'.sql';
system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile");
compress($backupfile);
// Send E-mail notification
$sendto = "NAME <E-MAIL ADDRESS>";
$sendfrom = "NAME <E-MAIL ADDRESS>";
$sendsubject = "SUBJECT";
// $message="This attachment contains the backup of your database.";
$separator = md5(time());
// attachment name
$filename = $backupfile.".zip";
// Open db file
$file = fopen( $backupfile, "r" );
// Read the file into a variable
$size = filesize($backupfile);
$content = fread( $file, $size);
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
// Define the main headers.
$header = "From:$sendfrom\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$separator\r\n";
$header .= "--$num\r\n";
// Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$separator\r\n";
// Define the attachment section
$header .= "Content-Type: application/octet-stream; ";
$header .= "name=\"$filename\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"$filename\"\r\n\n";
$header .= "$attachment\r\n";
$header .= "--$separator--";
// Send email now
mail( $sendto, $sendsubject, "", $header );
// Delete the SQL and ZIP file from your server
unlink($backupfile);
unlink($filename);
?>
If you add --verbose 2> output.txt to your command, it will spell out what is happening, line by line as below for example. Obviously you need to look at the contents of output.txt after the command.
-- Connecting to localhost...
-- Retrieving table structure for table users...
-- Sending SELECT query...
-- Retrieving rows...
-- Disconnecting from localhost...
Your full command would then be:
"mysqldump --opt -h $dbhost -u $dbuser -p $dbpass --verbose 2> output.txt". "$dbname | gzip > $backup_file"
Also it may not be correct to test $sys like you have done as an indicator of success, Instead use this form..
system ( string $command, &$return_var);
and then $return will contain the return status of the executed command (mysqldump) which is better for testing actual success of the backup.
Your code might then look like:
int $return_var;
system ($command, &$return_var);
if ($return_var ==0){
echo "success";
}
else{
echo "failed";
}
i changed a bit to support utf8
<title><?php echo "backup MySQL data - " . $_SERVER['SERVER_NAME'] ; ?></title>
<?php
// ref. to https://stackoverflow.com/questions/52530833/how-to-take-backup-of-mysql-database-using-php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'jackycms2019';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_set_charset($connection,"utf8");
$backupAlert = '';
$tables = array();
$result = mysqli_query($connection, "SHOW TABLES");
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($connection, "SELECT * FROM " . $table);
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$num_fields = mysqli_num_fields($result);
if (!$num_fields) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= 'DROP TABLE ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
if (!$row2) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$backup_file = $dbname . '.sql';
$handle = fopen("{$backup_file}", 'w+');
fwrite($handle, $return);
fclose($handle);
$backupAlert = 'backup MySQL data completed !';
}
}
}
}
echo $backupAlert;
?>

PHP not displaying database on website

I've compiled the following PHP and HTML, what I want to do is connect my WAMP database to my webpage, it's a simple task but the output i receive is displayed in the picture below, can somebody show me where i went wrong?
<?php
//Step 1
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>
PHP connect to MySQL
</h1>
<?php
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
?>
</body>
</html>
PHP and HTML error
I have found some errors in that code
$query = "SELECT * FROM patients";
You need to add the semicolon a the end of the query code here, so:
$query = "SELECT * FROM patients;";
Then we have this
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
This should work
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$patientname = $row['patient_name']; //do this with every variable you have
echo "$id $patientname";
}
EDIT: Also, change this
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
with this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hospital";
$db = mysqli_connect($dbhost,$dbuser,$dbpass) or die ("dbconn");
mysql_select_db($dbname,$db) or die ("msq");
You dont need to assign
$row = mysqli_fetch_array($result); as you are assigning it inside the while loop
EDITED ANSWER
Build a sperate array from the rows and then loop over that, this way you will have more flexibility to add to or edit the results before displaying them
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = $row;
}
foreach($rows as $r) {
echo $r['id'] . ' ' . $r['patient_name']. ': ' . $r['check_in_date'] . ' ' . $r['room_number'] . ' ' . $r['bed_number'] . ' ' . $r['notes'] . '<br />';
}

Multiple Variables in PHP URL with HTTP Referrer

I'm trying to create a custom URL with HTTP_Referrer (where they came from), the date, and an incrementing traffic URL
mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database');
mysql_query("INSERT INTO table (TrafficID, ClickURL, CreateDate) VALUES('".mysql_real_escape_string($_GET['TrafficID'])."', '".mysql_real_escape_string($_GET['ClickURL'])."', '".mysql_real_escape_string($_GET['CreateDate'])."')");
mysql_query("UPDATE table_name SET out = out + 1 WHERE ID = $TrafficID")or die(mysql_error());
$data = mysql_query("SELECT * FROM table_name WHERE ID = $TrafficID") or die(mysql_error());
$info = mysql_fetch_array($data);
$variable['TrafficID'] = "id";
$variable['ClickURL'] = "url";
$variable['CreateDate'] = "date";
$value['TrafficID'] = "mysql_fetch_array($data);";
$value['ClickURL'] = "$_SERVER['HTTP_REFERER']";
$variable['CreateDate'] = "$today";
$link = "http://www.example.com/page.php";
$link .= "?";
$link .= $variable['TrafficID'] . "=" . $value['TrafficID'];
$link .= "&";
$link .= $variable['ClickURL'] . "=" . $value['ClickURL'];
$link .= "#";
$link .= $variable['CreateDate'] . "=" . $value['CreateDate'];
echo "<a href='" . $link . "'>Click here!</a>";`
Ideally the URL would look like http://www.example.com/page.php?TrafficID&ClickURL#date and this would all be stored in the database, however I can't seem to get it to work, can anyone point where I made a mistake?
UPDATE
$value['ClickURL'] = "$_SERVER['HTTP_REFERER']";
$today = date("Ymd");
$variable['CreateDate'] = "$today";
$link = "http://www.example.com/page.php";
$link .= "?";
$link .= $variable['TrafficID'] . "=" . $value['TrafficID'];
$link .= "&";
$link .= $variable['ClickURL'] . "=" . $value['ClickURL'];
$link .= "&";
$link .= $variable['CreateDate'] . "=" . $value['CreateDate'];
echo "<a href='" . $link . "'>Click here!</a>";`
Changed # to & and reformatted my date value

Using multiple tables in a search engine?

To clean and tidy-up my code, I want to add multiple tables with the fields:
id
title
description
keywords
link
but I also want them in sections so in MySql I want different tables with categories such as: "News", "Social Networking" and "Shopping", but how can I get that? This is my code:
<?php
if( count($terms) == 0){ // If no terms entered, stop.
echo "No Search Terms Entered.";
}else{
// connect
$connect = mysql_connect("XXX", "XXX", "YYY") or die('Couldn\'t connect to MySQL Server: ' . mysql_error());
mysql_select_db("theqlickcom_774575_db1", $connect ) or die('Couldn\'t Select the database: ' . mysql_error( $connect ));
/* Query Statement Building - Terms together */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
/* Query Statement Building - Terms Separate */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
}
//disconnect
}
?>
If you have to search multiple table with one query
1.use mysqli
2.use UNION ALL in query
Join table
use mysql procedure

How to got trough the mysql results in php

I am getting error: Invalid argument supplied for foreach()
This is my class for connecting to database:
class dbMySql {
static function Exec($query) {
// open database
$conn = mysql_connect('localhost','root','****');
if($conn == false) {
throw new Exception(mysql_connect_error());
}
mysql_select_db('data',$conn);
$result = mysql_query($query,$conn);
if(is_bool($result) && !$result) {
$error = mysql_error($conn);
mysql_close($conn);
throw new Exception($error);
}
mysql_close($conn);
return $result;
}
}
And I have this code:
echo '{ "results" : [ ';
$gettruck_result = dbMySql::Exec("SELECT id, name, lat, lng FROM data)");
$result_array = array();
foreach($gettruck_result as $row) {
$row_object = '{';
$row_object .= '"id": "' . $row['id'] . '", ';
$row_object .= '"name": "' . $row['name'] . '", ';
$row_object .= '"lat": "' . $row['lat'] . '", ';
$row_object .= '"lng": "' . $row['lng'] . '", ';
$row_object .= '}';
$result_array[] = $row_object;
}
$result_str = implode(", ", $result_array);
echo $result_str;
echo " ] }";
?>
Any idea why am I getting error in foreach loop?
You have to replace:
foreach($gettruck_result as $row) {
... with ...
while($row = mysql_fetch_assoc($gettruck_result)) {
You have checked result array is empty or not..
if(mysql_num_rows($gettruck_result)>0)
{
foreach($gettruck_result as $row) {
.
.
}
}

Categories