selecting from a delimited string - mysql

I am using dotProject (OpenSource project management tool) and need do some custom sql selections for my own purposes.
select u.user_username,
p.project_name,
p.project_start_date,
p.project_end_date,
SUBSTRING(sysval_value,LOCATE(CONCAT(p.project_status,'|'),sysval_value)+2,LOCATE('\n',sysval_value,LOCATE(CONCAT(p.project_status,'|'),sysval_value))-LOCATE(CONCAT(p.project_status,'|'),sysval_value)-2) as project_status
from project_contacts pc
left join users u on pc.contact_id = u.user_id
left join sysvals s on s.sysval_title='ProjectStatus'
left join projects p on p.project_id=pc.project_id
notice the nasty way I had to select the ProjectStatus from the sysvals table.
The sysval_value for ProjectStatus looks like the following:
0|Not Defined/n1|Proposed/n2|In Planning/n3|In Progress/n4|On Hold/n5|Complete/n6|Template/n7|Archived
Not sure why it is like this, I would have expected a status table with a primary key and a description (maybe just to eliminate the number of tables in the project).
Is there a better way of selecting from this sort of delimited string in MySQL?

These sysval_values can be taken as an array with usingdPgetSysVal() method:
this method defined in dotProject->includes -> main_functions.php
$arr = array();
$arr=dPgetSysVal("ProjectStatus");
$arr[0]----------> Not Defined
$arr[1]----------> Proposed
$arr[2]----------> In Planning
$arr[3]----------> In Progress
$arr[4]----------> On Hold
$arr[5]----------> Complete and so on...
Here what i tried with your code for selection:
<?php
require_once 'base.php';
require_once DP_BASE_DIR . '/includes/config.php';
require_once (DP_BASE_DIR . '/classes/csscolor.class.php'); // Required before main_functions
require_once (DP_BASE_DIR . '/classes/kses.class.php'); // Required before main_functions
require_once (DP_BASE_DIR . '/includes/main_functions.php');
require_once (DP_BASE_DIR . '/includes/db_adodb.php');
require_once (DP_BASE_DIR . '/includes/db_connect.php');
require_once (DP_BASE_DIR . '/classes/ui.class.php');
require_once (DP_BASE_DIR . '/classes/permissions.class.php');
require_once (DP_BASE_DIR . '/includes/session.php');
require_once (DP_BASE_DIR . '/includes/permissions.php');
require_once (DP_BASE_DIR . '/style/dp-grey-theme/overrides.php');
$q = new DBQuery;
$q->clear();
$q->addTable('project_contacts');
$q->addTable('users');
$q->addTable('projects');
$q->addTable('sysvals');
$q->addWhere('dotp_project_contacts.contact_id = dotp_users.user_id');
$q->addWhere('dotp_sysvals.sysval_title = "ProjectStatus"');
$q->addWhere('dotp_projects.project_id = dotp_project_contacts.project_id');
$values = $q->loadList();
$arr = array();
foreach ($values as $row) {
$arr=dPgetSysVal("ProjectStatus");
echo $row['user_username'].' '. $row['project_name'].' '. $row['project_start_date'].' '. $row['project_end_date'].' '. $arr[$row['project_status']].'<br>';
}
?>
dotp_ my db table extension :)

Related

Database not working on the root of Wordpress theme

I have created my own table on my wordpress database and created the filter search form. Now, my problem is that, I dont know how to connect my database to my search filter form in wordpress.
Here is the process, I send the keyword from index.php to result.php, and it shows nothing, just a blank page.
Here's my code:
<?php
define('WP_USE_THEMES', false);
global $wpdb;
$destination = $_POST["destination"];
echo "Welcome test" . $destination;
$sql = "SELECT * FROM rates WHERE location = '" . $destination ."';";
echo $sql;
echo "search this";
foreach ( $wpdb->get_results($sql) as $result ) {
echo "search for". $result->location;
}
?>
wp-content/themes/Your-Theme-Name/result.php
<?php
/*
* Template Name: MyResultPage
*/
/* You can also use require_once('wp-load.php'); */
get_header();
global $wpdb;
$destination = $_POST["destination"];
$table = $wpdb->prefix . "rates";
$sql = "SELECT * FROM `". $table . "` WHERE location = '". $destination. "'" ;
$result = $wpdb->get_results($sql);
foreach($result as $res) {
echo "search for". $res->location;
}
?>
Then, you create a new page in your wordpress admin and set the template to result.php template name: MyResultPage (for example).
you should either include wp-config.php file in the header of the file which will include all the relevant files in your page.
Can you plz check below code and it output.
i added one page in root directory of WordPress and make one page and add this code.
test.php
<?php
define('WP_USE_THEMES', false);
require_once('wp-load.php');
global $wpdb;
$result = $wpdb->get_results(("SELECT * FROM {$wpdb->prefix}posts WHERE post_type = 'page'"), ARRAY_A);
foreach( $result as $key => $val )
{
echo '<p>Title - '.$val['post_name'].'</p>';
echo '<p>ID - '.$val['ID'].'</p>';
}
?>
Now here is out put of this page it shows all page title and id.
Output:
<p>Title - sample-page</p>
<p>ID - 2</p>
<p>Title - sample-page1</p>
<p>ID - 3</p>

Inserting a table in a database without knowing prefix

I have a small script that will insert two tables in a database, which works fine unless the user has changed the default prefix. I am wondering how I can call and use the "prefix" from the config file. Here is my code.
<?php
include("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'], $CONFIG['password'];
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
You can see that I call "config.php" to get the database info. That would also work to get the prefix but I'm not sure how to implement the "prefix" with the rest of the code.
FYI: I'm a newbie :)
Thanks.
I got it, here's what worked.
<?php
require_once ("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'],$CONFIG['password']);
$table_prefix = ($CONFIG['prefix']);
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO ' . $table_prefix . 'settings'.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
Thanks for the help BK435
Welcome!
I am assuming you can get the prefix and store it in variable. When calling your sql add this to your code ' . $TABLE_PREFIX . '. so your above insert would look something like:
$sql = 'INSERT INTO ' . $TABLE_PREFIX . 'settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';

Retrieve particular field from serialized data

Suppose I have following data :
a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}
I want the value of mm and dd from that serialized string.
I have following query to retrieve above data :
$birthday = "select meta_key, meta_value from $wpdb->usermeta where meta_key='pie_date_5'";
$user_birthday = $wpdb->get_results($birthday);
foreach($user_birthday as $ubday){
$ubd = $ubday->meta_value; echo $ubd;
echo json_decode($ubd[0]->mm);
}
I am not able to do that simple thing. Please help me out.
You have to use unserialize instead of json_decode because it's a serialized string.
So you could try something like this:
$user_birthday = 'a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}'; //the serialized string you get from your query
$upday = unserialize( $user_birthday );
echo $upday['date']['mm'] . PHP_EOL;
echo $upday['date']['dd'];
EDIT: If you want to read all properties from the $upday array you could use a foreach-loop
foreach ( $upday['date'] as $key => $value ) :
echo $key . ' = ' . $value . PHP_EOL;
endforeach;

Mysql UPDATE syntax, how to use as array

I'm having trouble understanding the documentation for the UPDATE command of MYSQL. I am viewing records in a PHP page from the database and I want to edit them.
To INSERT I have this code which is an array. I want to know if I can do the same with the UPDATE statement, to save me lots of this=$this 's.
Insert
mysql_query("INSERT INTO $tbl_name(title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog')")or die(mysql_error());
Update
mysql_query("UPDATE $tbl_name SET title='$title', pbDate='$pbDate' summary='$summary' blog='$blog' WHERE id='$id'")
I thinking something like this, but I'm not sure and can't find anything in the manual.
mysql_query("UPDATE $tbl_name SET (title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog') WHERE id='$id'")
You could use an array ...
Working phpFiddle:
http://phpfiddle.org/main/code/pi9-ckh
<?php
$array = array(
"column" => "some_value",
"title" => "some_title",
);
$setString = '';
foreach($array as $key => $value){
$tempArray[] = $key . ' = ' . "\"" . $value . "\"";
}
$setString = implode(",", $tempArray);
echo $setString;
?>

Displaying MYSQL data in a HTML table AFTER a search

I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX"; 
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.