connection php and postgreSQL - php

I'm have a problem. I want connect PHP and PostgreSQL, but don't know how.
HTML:
<?php
?>
<!DOCTYPE html>
<html lang = "pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Título -->
<title>test</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Font-Awesome CSS -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- Ubicua-cloud CSS -->
</head>
<body>
<form action = "" name = "f1" method = "post" style = "">
<input type = "text" id = "telefone">
<button type = "button" id = "init">iniciar sessão</button>
</form>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="js/bootstrap.min.js"></script>
<!-- Ubicua-cloud-js -->
<script src="login.js"></script>
</body>
</html>
DB connect:
<?php
$connect=pg_connect ("host=localhost dbname=test port=5432 user=postgres password=28974220")or
die("Error");
?>
JS to catch user informations:
$(document).ready(function(){
$('#init').click(function(){
var telefone=$('#telefone').val();
alert(telefone);
$.ajax({
type:"POST",
dataType:'json',
url:'login.Ajax.php',
data:{telefone:telefone},
success: function(response){
if(response.resposta==true){
$('#msg').html(response.msg);
window.location='test.php';
}
else{
$('#msg').html(response.msg);
}
},error:function(){
alert('error');
}
});
});
});
The PHP code to validate informations:
<?php
include_once('includes/connect.php');
$msg_ok=false;
$msg_error='O sistema está indisponível.';
if(isset($_POST['telefone']))
if($_POST['telefone']!="")
$telefone=$_POST['telefone'];
$consulta=pg_query($connect, ("Select * from test where telefone='$telefone"));
if(pg_num_rows($consulta)>0)
$msg_ok=true;
$usua=pg_fetch_array($consulta);
session_start();
$_SESSION['id']=$usua[0];
$_SESSION['telefone']=$usua[1];
$msg_error='Logado';
else
$msg_error='Telefone não existe.';
endif;
else
$msg_error='Telefone incorreto.';
endif
else
$msg_error='Erro.';
endif;
$saidaJson=array('resposta' => $msg_ok, 'msg' => msg_error);
echo json_encode($saidaJson);
?>
I received error messages to catch user informations, help, please.

I'm assuming you are using PDO. If so, you need make changes to the database connection file(substitute the variables with your database values):
<?php
$db = new PDO("pgsql:dbname=$dbname;host=$host";port=$port, $dbuser, $dbpass);
?>

I solved the problem, but now I'm needing exchange informations between the php and js...I have a script that simulates a person typing and need it to talk to users calling them by their proper names, but I don't know how, I need concatenate one variable in JS, but before that I need store one PHP variable in one JS variable.
var init = document.getElementById('init_text');
var init_text = 'Hi <nome>, I'm your friend!';
function digit(str, el) {
var char = str.split('').reverse();
var typer = setInterval(function () {
if (!char.length) return clearInterval(typer);
var next = char.pop();
el.innerHTML += next;
}, 60);
}
digit(init_text, init);

Related

How to code my MySQL data into Bootstrap input tags with autocomplete?

I'm creating this bootstrap input tag in my project using PHP.
Now, how can I populate the restrictTo and suggestions with data from MySQL?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Send Memorandum</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/memo.css" rel="stylesheet">
<link href="css/bootstrap-tags.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="send.php" method="post" class="memo" style="padding-top:10px">
<div class="form-group row">
<div class="col-xs-8">
<label for="To" style="padding-top: 10px;" >To: </label><br>
<p>suggestOnClick</p>
<div id="suggestOnClick"></div>
</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-tags.min.js"></script>
In this section i want to make the default value of the suggestions: to be removed and then replace it with my MySQL data values like "SELECT account_username FROM tbaccounts" into the suggestion: and restrictTo: Is that possible?
So this is my SCRIPT
<script>
$(function(){
$("#suggestOnClick").tags({
restrictTo: ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india"],
suggestions: ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india"],
promptText: "Click here to add new tags",
suggestOnClick: true
});
});
</script>
</body>
</html>
This is my PHP
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "fullcalendar");
$query = "
SELECT * FROM tbaccounts ORDER BY account_username
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["account_username"];
}
echo json_encode($data);
}
?>
Now, How can i put this json_enccode($data); to restricTo: and suggstions: in the SuggestOnClick Funtion?
You can always use jquery ajax.
js file
var app={
init:function(){
$(document).ready(this.initialize);
},
initialize:function(){
$.ajax({
url:'php/fetch.php',
METHOD:'GET',
success:function(data){
data=JSON.parse(data);
$("#suggestOnClick").tags({
restrictTo: data,
suggestions: data,
promptText: "Click here to add new tags",
suggestOnClick: true
});
}
});
}
};
app.init();
php/fetch.php
echo json_encode(array("alpha","bravo","charlie"));

jQuery Mobile loads content only after I hit refresh

My jQuery Mobile page does not load content via $.get which is bind into pageinit event, but does so when I hit refresh (F5), why is that so?
My HTML page igra.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- stili za custom temo, jquery, jquery mobile, phonegap-->
<link rel="stylesheet" href="themes/what.min.css" />
<link rel="stylesheet" href="jquerymobile.css" />
<script src="jquery191.js"></script>
<script src="jquerymobile.js"></script>
<script src="phonegap.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="stil.css" />
</head>
<body>
<div data-role="page" id="igra">
<div data-theme="a" data-role="header">
347 coins
<h3>WHAT?</h3>
Home
</div>
<div data-role="content" class="igracontent"> </div>
</div>
</body>
</html>
My main.js with jQuery Mobile code:
$( document ).delegate("#igra", "pageinit", function() {
var par = qs["battlefield"];
$.get('igra.php?battlefield='+par, function(data2) {
$('div.igracontent').append(data2).trigger('create');
});
});
//parse url parameter
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
In igra.php I make SQL query and retrieve some data which I format in jQuery Mobile style and echo it back.
I know jQuery Mobile does not load head into DOM in subsequent pages, so main.js is also included in index.html head which is landing page of my app. All transitions to new pages are by normal ajax querying (I do not prevent default behaviour).
So what happens? When I navigate to igra.html?battlefield=3 the pageinit event does happen but content which I load via $.get from php page does not get inserted! If I hit F5(refresh) the content does get loaded into page. Can anybody explain and help? :) Thank you!

Pass javascript variable to server side in php sql query

I have a javascript variable from a previous page that is passed to the header as "namer". Now I also want to use that variable in a sql query in php. How do I go about sending this javascript variable to php on the server side as the variable "namer"?
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"> </script>
</head>
<body>
<script>
$( document ).ready(function() {
var namer = sessionStorage.getItem("namer");
$('h1').text(namer)
});
</script>
<div data-role="page" class="div1">
<div data-role="header">
<h1>"namer"</h1>
</div>
<div data-role="content">
<?php
$link = mysql_connect("xxxx", "xxxx", "xxxx") OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db("abxusername");
$query = "SELECT class FROM Antibiotics WHERE name="."namer".";";
echo $query;
echo mysql_query($query);
?>
</div>
</div>
</body>
</html>
If it's not sensitive data and you can afford a reload, just use a GET variable.
client side (javascript)
document.location.href = "?namer=" + namer
Server side (PHP)
if (isset($_GET['namer']) && !empty($_GET['namer'])){
$namer = $_GET['namer'];
// Now sanitize data and use it on your SQL query
}

How to pass database id in jquery

i want to delete a record that are showing in while loop from the database but before deleting i want to display a confirmation box.The code i have written is below.it is working fine but to delete record i need to pass an id that i haave described in the code
------index.php starts
<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
<div class="item">
<div class="delete"></div>
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
----index.php ends
----jquery.confirm.js file starts
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
----jquery.confirm.js file ends
-----script.js file starts
$(document).ready(function(){
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
elem.slideUp();
//sql delete query will be written here... in where condition i need to pass the fetched record id from index.php file in where condtion
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
-----script.js ends
You can use the html data attribute and retrieve it with .data jQuery method
In your HTML:
<div class="delete" data-id="{$id}"></div>
In your Javascript
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
var id = elem.data('id'); /* this is your db id */
});
Are you sure you want to send a query from Javascript? The usual way to do this is to send a request (via jQuery) with that specific id, to a script which runs the query (server side), and returns a response.
Now, since you add the item divs, using a while, why not add an id property to the divs, which contain the id from the database, something like
<div id="item<?php echo $row['id'];?>" class="item">
<div class="delete">
</div>
This way, the $('.item .delete').click handler has access to the item's id, by parsing the target's id property, and you don't need to pass it explicitly to jQuery.
Here you can use hidden field to save value for id and then use jquery to retrieve it from hidden field..
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<input type="hidden" id="hid_id" value="<?php echo 'fetched id';?>" />
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
And then in jquery when using confirm box you can get value by id hid_id .

Saving Changes in SlickGrid with php

I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>

Categories