php, connecting to database using mysql_connect() problem, how to? - php

i am using some php and ajax to make a call to a database and i get this error: Warning: mysql_query() [function.mysql-query]: A link to the server could not be established... and Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
now from what i read looks like i need to create a database connection first, and the problem is that i am.
I am using require_once ('db_connect.php'); at the begining:
<?php
define("HOST", "localhost");
define("DBUSER", "123");
define("PASS", "123");
define("DB", "123");
$prefix = "";
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die('Could not connect !<br />Please contact the site\'s administrator.');
$db = mysql_select_db(DB) or die('Could not connect to database !<br />Please contact the site\'s administrator.');
?>
My script looks something like this (ignore any missing or broken html):
<?php
session_start();
require_once ('db_connect.php'); // include the database connection
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<html>
<head>
</head>
<body>
<div id="wrap">
<script type="text/javascript">
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var com_type = 1;
var email = $("#email").val();
var comment = $("#comment").val();
var post_id = $("#post_id").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&post_id=' + post_id;
if(name=='' || email=='' || comment=='')
{
alert('Please Give Valide Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('email').value='';
document.getElementById('name').value='';
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<div id="main">
<ol id="update" class="timeline">
<?php
$sql=mysql_query("select * from comments where post_id_fk='$post_id'");
while($row=mysql_fetch_array($sql))
{
$name=$row['com_name'];
$com_type=$row['com_type'];
$email=$row['com_email'];
$comment_dis=$row['com_dis'];
$lowercase = strtolower($email);
$image = md5( $lowercase );
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=<?php echo $image; ?>" class="com_img">
<span class="com_name"> <?php echo $name; ?><?php echo $com_type; ?></span> <br />My Comment</li>
<?php
}
?>
</ol>
<div id="flash" align="left" ></div>
<div style="margin-left:100px">
<form action="#" method="post">
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>"/>
<input type="text" name="title" id="name"/><span class="titles">Name</span><span class="star">*</span><br />
<input type="text" name="email" id="email"/><span class="titles">Email</span><span class="star">*</span><br />
<textarea name="comment" id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
</div>
</div>
</body>
</html>
the connectajax.php :
<?php
if($_POST)
{
$name=$_POST['name'];
$name=mysql_real_escape_string($name);
$com_type=$_POST['com_type'];
$name=mysql_real_escape_string($com_type);
$email=$_POST['email'];
$email=mysql_real_escape_string($email);
$comment=$_POST['comment'];
$comment=mysql_real_escape_string($comment);
$post_id=$_POST['post_id'];
$post_id=mysql_real_escape_string($post_id);
$lowercase = strtolower($email);
$image = md5( $lowercase );
mysql_query("insert into comment(com_name,com_type,come_email,com_dis) values ('$name','$com_type','$email','$comment_dis','$post_id')");
}
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=
<?php echo $image; ?>"/>
<?php echo $name;?><br />
<?php echo $comment; ?>
</li>
any idea?
thanks

You didn't require_once the db_connect.php script in your connectajax.php script (unless you omitted that line when copying the code in).

Sounds to me as though your mysql service is down. Try reloading it. If that doesn't work, maybe try connecting to a mysql database on another server, to see if maybe it's not the mysql service's fault.

Check if you have given proper access rights to Mysql database...
that will resolve this issue

Related

Unable to save timestamp to sql database from form data

Im trying to save the current timestamp of the video being played as soon as I click submit. But in the table only 0 is getting saved and Im unable to fetch & save the current timestamp of video. Although its getting displayed but not getting saved in SQL table.
NOTE : timestamp(tstamp) : Is a dynamic value, which is the timestamp of the video file being played in the browser( for example 1.935771),
fileUpload.php
<body>
<h1>VIDO LABELLING TOOL</h1>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268"
data-setup='{ "playbackRates": [0.5, 1, 1.5, 2, 4] }'>
<source src="project.m4v" type='video/mp4'>
<track src='br.srt' kind="subtitles" srclang="en" label="English" default>
</video>
<script>
// Get the audio element with id="my_video_1"
var aud = document.getElementById("my_video_1");
// Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
aud.ontimeupdate = function () {
myFunction()
};
</script>
<div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">
<form name="contact-form" action="" method="post" id="contact-form">
<label for="email">Comments about the frame</label>
<textarea name="message" class="form-control" id="message"></textarea>
<div class="error" id="error_message"></div>
<label>Vehicle Type:</label>
<input name="veh_type_1" id="veh_type_1" type="checkbox" value="lmv">lmv
<input name="veh_type_2" id="veh_type_2" type="checkbox" value="2w">2w
<p>TimeStamp: <span id="tstamp"></span></p>
</div>
<p class="submit">
<button type="submit" class="btn btn-primary" name="submit" value="Submit" id="submit_form">Submit</button>
</p>
<div class="display-content">
<div class="message-wrap dn"> </div>
</div>
</form>
</div>
<script>
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#contact-form").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: "saveFile.php",
data: $(this).serialize(),
success: function () {
alert("form was submitted");
}
});
return false;
});
});
</script>
</body>
and the php file for db update as :-
saveFile.php
<?php
$servername = "localhost";
$database = "stackover";
$username = "root";
$password = "123456";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$tstamp = addslashes($_POST['tstamp']);
$message = addslashes($_POST['message']);
$veh_type_1 = addslashes($_POST['veh_type_1']);
$veh_type_2 = addslashes($_POST['veh_type_2']);
mysqli_query($conn, "insert into saveData(message,tstamp,veh_type_1, veh_type_2) values ('$message','$tstamp','$veh_type_1', '$veh_type_2')");
$sql = mysqli_query($conn, "SELECT message,tstamp,veh_type_1,veh_type_2 id FROM saveData order by id desc");
$result = mysqli_fetch_array($sql);
echo '<div class="message-wrap">' . $result['message'] . '</div>';
?>
Please add this into your form
<input name="tstamp" id="hidden-tstamp" type="hidden">
and inside your script add below code
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
document.getElementById('hidden-tstamp').value = aud.currentTime;
}

PHP:unable to echo a variable from DB

I'm writing a chat script but I have problem with echo some variables!
I have written this piece of code in chat.php to show the messages:
<?php
session_start();
$id=$_GET['id'];
if(isset($id)){
global $id;
global $qs;
global $answerer;
global $sp;
global $name;
include('config.php');
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$id=$conn->quote(htmlentities($id));
$find=$conn->prepare("SELECT * FROM qs WHERE id=:id");
$find->bindParam(':id',$id);
$find->execute();
if($rows=$find->fetch(PDO::FETCH_ASSOC)){
$qs=$rows['question'];
$answerer=$rows['answerer'];
}
$answerer=explode("(",$answerer);
$ansgiver=$conn->prepare("SELECT * FROM ruhani WHERE name=:answerer");
$ansgiver->bindParam(':answerer',$answerer[0]);
$ansgiver->execute();
if($row=$ansgiver->fetch(PDO::FETCH_ASSOC)){
$name=$row['username'];
$avatar=$row['avatar'];
$sp=$row['sp'];
}
class chat {
public function fetchMessage() {
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$ans=$conn->prepare("SELECT answere FROM ans WHERE q_id=:id ");
$ans->bindParam(':id',$id);
$ans->execute();
}
public function throwMessage($id, $text,$sayer){
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$send=$conn->prepare("INSERT INTO ans(q_id,answere,sayer) VALUES(:q_id,:text,:sayer) ");
$send->bindParam(':q_id',$id);
$send->bindParam(':text',$text);
$send->bindParam(':sayer',$sayer);
$send->execute();
}
}
$chat = new chat();
?>
<!DOCTYPE html>
<head>
<title>Example Title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style/style.css" media="screen, projection" />
<script src="js/jquery-1.6.3.min.js"></script>
<script src="js/chat.js"></script>
</head>
<body>
<div class="all">
<div class="env">
<span><?php echo $name ?>|<?php echo $sp ?></span>
<span>Hi,Can I help you?</span><br>
<span>me:<?php echo $qs ?></span>
<div class="messages"></div>
</div>
<textarea name="ask_ans" class="ask_ans" id="ask_ans" placeholder="Please write here!"></textarea><br>
<input type="submit" class="submit" name="submit" value="send" />
<input type="hidden" id="hidden" value=<? echo $id ?> />
<input type="hidden" id="hidden2" value=<? echo $_SESSION['$username'] ?> />
</div>
</body>
<?php
}
?>
and this code for Ajax part(chat.js):
var chat = { }
chat.fetchMessage=function (){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'fetch'},
cache:false,
success: function(data){
$(".all .env .messages").html(data)
}
});
}
chat.throwMessage=function (id,message,sayer){
if($.trim(message).length != 0 ){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'throw' , id : id , message : message , sayer : sayer },
cache:false,
success: function(data){
chat.fetchMessage();
$(".ask_ans").val('');
}
});
}
}
chat.entry=$(".all .submit");
chat.entry.bind('click',function (evt){
evt.preventDefault();
chat.throwMessage($("#hidden").val(),$(".ask_ans").val(),$("#hidden2").val());
});
chat.interval=setInterval(chat.fetchMessage(),5000);
chat.fetchMessage()
And this is send.php:
<?php
require('chat.php');
if (isset($_POST['method']) and !empty($_POST['method'])){
$chat =new chat();
$method =trim($_POST['method']);
if ($method === 'fetch'){
$messages=$chat->fetchMessage();
if (!empty($messages)){
while($r=$messages->fetch(PDO::FETCH_ASSOC)){
$sayer=$r['sayer'];
if($sayer===$starter){
?>
<span class="text" style="float:left"><? echo $r['answere'] ?></span>
<?php
}else{
?>
<span class="text" style="float:right"><? echo $r['answere'] ?></span>
<?php
}
}
}
}else if ($method === 'throw'){
$message=trim(htmlentities($_POST['message']));
$id=trim(htmlentities($_POST['id']));
$sayer=trim(htmlentities($_POST['sayer']));
if(!empty($message) and !empty($id) and !empty($sayer)){
$chat->throwMessage($id,$message,$sayer);
}
}
}
?>
I am getting an error:
Undefined index:id
My problem is that I can't echo $qs,$name,$sp in chat.php.
Can anyone understand the wrong part of my code?
After long time I checked my code,I understand the problem:)
As you see I'm using PDO::quote() and it puts ' ' over the word.So that When I was exploding the variable here:$answerer=explode("(",$answerer);,it couldn't find the correct word to search in DB and didn't echo the variable.
And now I have deleted PDO::quote() and my code is working correct.:-)

How to insert into MySQL HTML Form data?

I checked a lot of articles and I don't understand it how to insert data into a MySQL table. What is wrong? I guess that my Ajax request is already wrong.
I would be happy to get help!!!
I did not write programs since 20 years. My coding is for sure not good, but I need to get it running.
Any help would be very appreciated!
The code that follows does not INSERT INTO and does not UPDATE. Why?
Here is the source:
articles.php
<!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" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var lastPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// No submit by onclick
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordInsertWrite()
{
document.getElementById('formheadline').innerHTML = 'Article Database - I save the new item';
document.getElementById("recordWrite").disabled = true;
js_articles[0]=""; // set auto increment id to NULL
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'writearticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr id="buttonarea">
<td align="right" colspan="2">
<hr noshade="noshade" />
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value=" Save New Record " onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div id="aside">
</div>
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
</body>
</html>
writearticle.php
<?php
$link = mysql_connect('test.test.com:3306', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
// Escape user inputs for security
$ID = mysql_real_escape_string($_POST['ID']);
$Item = mysql_real_escape_string($_POST['Item']);
$ItemCategory = mysql_real_escape_string($_POST['ItemCategory']);
if('$ID' == '')
{
$sql = "INSERT into articles values(NULL,'$Item','$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("error");</script>';
}
else
{
echo '<script type="text/javascript">alert("ok");</script>';
}
}
else
{
$sql = "UPDATE articles SET Item='$Item',ItemCategory='$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("update error");</script>';
}
else
{
echo '<script type="text/javascript">alert("update ok");</script>';
}
}
?>

how to push notification on all user in database with php

this is my file php use jquery to send text from view to send_message.php based only for one id. i want change this code become send text from view to send_message.php to all id registered. you can see this code
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"]; ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php } ?>
<?php
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
this code send input from "txt_message" to user based id and "gcm_regid" so one txt_message for one id, but i try to send same txt_message for multiple id. help me, thank yuo

php code send notification to all devices GCM

I need a little help to send notification to all devices at once.
I know array need to be used for that but can't get the idea. A little hint will also work
DB table design
id gcm_regid name email created_at
Currently i have to fill out the form for all the devices and send notification one by one.
PHP code:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
EDIT: Or can anyone tell me how do i use checkbox for select all "id"s?

Categories