i am a newbie with php and im trying to use jquery grid, with the form edit, and delete.
I am implementing the edit , it is appearing - error Status: 'error'. Error code: 0 ,when i press the submit button ,the error apears but the changes are made...
my grid...
<script>
var lastsel;
$(function() {
$("#toolbar").jqGrid({
mtype: 'POST',
editurl: 'http://www.onetag.pt/eulen/edit.php',
caption:"Tags",
colNames:['TagID','Nome', 'Descricao', 'Tipo'],
colModel:[
{name:'tagID',index:'tagID',hidden:true},
{name:'name',index:'name',editable:true},
{name:'description',index:'description',editable:true},
{name:'type',index:'type'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar',
rowList:[10,20,30],
rowNum:10,
sortname:'tagID',
sortorder:'desc',
url:'/tags/list/',
viewrecords:true,
width:740
});
$("#toolbar").jqGrid('navGrid','#ptoolbar',{del:true,add:false,edit:true,search:true});
$("#toolbar").jqGrid('filterToolbar',{stringResult:true,searchOnEnter:false});
});
</script>
and the editurl.php
<?php
// connect to the database
$dbhost = "localhost";
$dbuser = "blah";
$dbpassword = "blah";
$database = "blah";
$tablename = "tags";
$db = mysql_connect($dbhost, $dbuser, $dbpassword)
or die("Connection Error: " . mysql_error());
mysql_select_db($database) or die("Error conecting to db.");
//mysql_set_charset('utf8',$database);
mysql_query("SET NAMES 'utf8'");
if($_POST['oper']=='add')
{
}
if($_POST['oper']=='edit')
{
$id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$sql = "UPDATE ".$tablename." SET name ='".$name."', description ='".$description."' WHERE tagID = ".$id;
$result=mysql_query($sql) or die(mysql_error());
mysql_close($db);
}
if($_POST['oper']=='del')
{
}
?>
i select the first row, and press edit button
then it appears the edit form...
then ive put the desired changes...
then press the submit button and the error appears...
i close the edit form, and press f5 to refresh, and the datafields have changed...
Related
i want to insert selected texts in my page in table with clicking on button in my page but my problem is it doenst insert . select text is correct i tested it.
response that i receive is my selected texts
This is my index page and i passed my texts into variable text
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var text = $("span:not([dir=rtl])").text();
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'text':text},
success:(function (response) {
alert(response);
})
})
})
})
</script>
this is my process.php that connects to database and perform query but runs else statement
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sahifeDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'update sahife_tbl set english ='. $_POST['text'].' where id=1 ';
$result = $conn->query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You need to put " in update statement as datatype is text for field
change your query to:
$sql = 'update sahife_tbl set english ="'. $_POST['text'].'" where id=1 ';
Also use Prepared statement to prevent from sql injection
You need to put quotes around your string value in the query otherwise your DB will try to parse the text as part of the syntax and fall over.
$sql = "update sahife_tbl set english ='". $_POST['text']."' where id=1 ";
But again as mentioned in my comment on your question, this is super insecure, you want to use parameterisation instead - https://stackoverflow.com/a/60496/635522
I am trying to subtract 0.05 from the cash amount of a player in my database once they push a button. Here is what I got so far.
My database:
Database name: accounts
Table: users
The Column I want to affect: cash_amount
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5ยข)</button>
Php file: (subtract5.php)
<?php
UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'
Thanks for helping, I am kind of a noob :)
This the following code, however dont exactly copy paste it, read the comments there are a few variables you might have to change and get from the database.
<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";
// Create connection
$userid = // You must enter the user's id here.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $previousAmount - 0.05;
$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Try executing that request. That's nothing more than a string without quotes around it. I'm sure that PHP considers it as an error.
You should consider learning PHP and MySQL before attempting to code a project.
I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});
I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}
So I need simple thing, I need to create button in my website, after button is clicked, It should truncate database table, but I can't do It successfully by myself. So could you help me, please?
Here I'm trying to creeate button:
<input type="button" id='delete' class='delete' value='Truncate' onClick="$truncate">
</input>
I know this is wrong way to use PHP variable in HTML, but I don't know how to do It correctly.
Here is my PHP variable:
$truncate= "TRUNCATE TABLE myTable";
With connection to database is all right:
$mysqli = new mysqli("localhost","database","password","asd");
So maybe here is better method to create button for truncate database's table? Thank you.
UPDATED:
This won't work too, nothing happens after button is clicked.
if(isset($_POST['delete'])){
$delete= "TRUNCATE TABLE myTable";
}
?>
<input type="button" id='delete' class='delete' name="delete" value='Truncate' onClick="delete">
</input>
Here, give this a try.
PHP (delete_table.php)
<?php
// CONNECT TO THE DATABASE
$DB_HOST = "your_host";
$DB_NAME = "your_DB_name";
$DB_USER = "username";
$DB_PASS = "password";
$dbc = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
or die('Error connecting to MySQL server');
if(isset($_POST['delete'])){
$query = "TRUNCATE TABLE `yourTable` "; // replace yourTable with one to delete
$result = mysqli_query($dbc,$query)
or die('Error deleting table.');
}
else {
echo "Sorry";
}
?>
HTML form
<form method="post" action="delete_table.php">
<input type="submit" id='delete' class='delete' name="delete" value='Truncate'></input>
</form>
I'm by far no jQuery expert but maybe something like this....untested of course
jQuery
$(document).ready(function() {
$('#delete').click(function() {
var table = $('#table').val(); //where #table could be an input with the name of the table you want to truncate
$.ajax({
type: "POST",
url: "truncate.php",
data: 'table='+ table,
cache: false,
success: function(response) {
alert('table dropped');
},
error: function(xhr, textStatus, errorThrown) {
alert('request failed');
}
});
});
});
PHP (truncate.php)
try {
// create a new instance of a PDO connection
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
$table = $_POST['table'];
$sql = 'TRUNCATE TABLE '.$mytable;
$stmt = $db->prepare($sql);
$stmt->execute();
?>