Passing php variable onclick gives error - javascript

Please see the scripts below. Onclick of Add gives an error when a php variable ($var)is used, however it will work with a number - i.e. if the line in index.php:
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>';
Is changed to something like:
echo '<button id="1" onclick="company_add(',57776,');">Add</button>';
What am I missing please?
Index.php:
<html>
<head>
<script type ="text/javascript">
function company_add(company_name) {
$.post('company_add.php', {company_name:company_name}, function(data) {
if (data == 'success'){
alert("Cool");
} else{
alert(data);
}
});
}
</script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<?php
include 'connect.php'; //Generic connect file
$var = 'Name';
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>
<br/>';
?>
</body>
</html>
company_add.php:
<?php
include 'connect.php';
function company_exists($company_name) {
return (mysql_result(mysql_query("SELECT COUNT(`company_name`) FROM
`company` WHERE `company_name` = $company_name"), 0) == 0 ) ? false :
true;
}
function add_company($company_name){
mysql_query("INSERT INTO `company` (`id`, `company_name`) values ('',
".$company_name.")");
}
$company_name = $_POST['company_name'];
if (company_exists($company_name) === true) {
echo 'Company already added';
} else {
add_company($company_name);
echo 'success';
}
?>

Use that line like this:
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
In case if you already have commas after and before the value of the $var you should trim it.
So use it like this:
$var = ltrim(",", $var);
$var = rtrim(", ", $var);
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
And for your information yes you can even use a String instead of a Number too.
And UPDATE the functions:
function company_exists($company_name) {
$company_name = mysql_real_escape_string($company_name);
$query = "SELECT * FROM company WHERE company_name = '{$company}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
return true;
}else{
return false;
}
}
function add_company($company_name){
$company_name = mysql_real_escape_string($company_name);
$query = "INSERT INTO company (id, company_name) VALUES ('', '{$company_name}')";
return mysql_query($query);
}
If you are using id field of that company table as AUTO_INCREMENT then you can leave the id field NAME & VALUE in the INSERT Statement.
Like This in the add_company Function:
$query = "INSERT INTO company (company_name) VALUES ('{$company_name}')"

Related

Alert box is not appear when I submit data

There are many similiar questions but I don't have any error, where I need to do changes.
I have put alert boxes in my code but non are appearing.
Here is my code-
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql))
?>
<script> alert('Data Inserted successfully');
window.location.href='student.php?id=<?php echo $id;?>' </script>
<?php
}
}
You can wrap the script tag with all the js in string and echo it. it will work
if($conn->query($sql)){
echo "<script> alert('Data Inserted successfully')window.location.href='student.php?id="+$id+"</script>";
}
Try this:
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql)){
echo "<script type='text/javascript'>alert('Data Inserted successfully');
window.location.href='student.php?id=".$id."';
</script>";
}
}
}

Remove a row inside a div

I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>

onclick delete will always delete the last row of the table

I have this inside a while loop. Everytime I confirm the onclick delete of any table row it always deletes the last row.
echo '<td><img src=img/view.png width=20px height=20px id="view"></td>';
echo '<td><img src="img/delete.png" width=20px height=20px name="delete"></td></tr>';
?>
<script type="text/javascript">
function deleteShit()
{
if (confirm('Delete?'))
window.location='delete.php?id=<?php echo $id;?>'
}
this is the delete.php page
$id=$_GET['id'];
$query = "UPDATE `main` SET status=0 where id = $id";
$sql = $db->prepare($query);
if ($sql->execute()) {
echo "<script>
window.alert('Item deleted!')
window.location='view.php';
</script>";
}
You must write your javascript function outer the while, with an arg :
<script type="text/javascript">
function deleteShit(id)
{
if (confirm('Delete '+id+'?')) {
window.location = 'delete.php?id='+id;
}
}
</script>
And call the function with the arg :
echo '<td><img src="img/delete.png" width=20px height=20px name="delete"></td></tr>';

Can not add a Comment using jquery php ajax

I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources