Somehow my query is not working when I click the button. What I'm trying to do is to TRUNCATE the table when the user click the button.
if(isset($_POST['extract'])){
#mysql_query("TRUNCATE TABLE temp");
}
I also tried this:
if(isset($_POST['extract'])){
$myquery = mysql_query("TRUNCATE TABLE temp");
}
Why is it not executing?
This is the html code:
<input type="submit" value="Extract CSV file" name="extract">
So here is how would approach to debugging this problem:
1) Check if the form is actually submitted. Put this on the top of your PHP file (note: for debugging only)
echo "I have reached my destination";
die();
2) Check if you are submitting via POST or GET. Or easier, replace $_POST with $_REQUEST, which contains both $_POST and $_GET.
if(isset($_REQUEST['extract'])){
3) Ensure the connection to the database is opened.
4) Provide your script the means to tell you if the query executed successfully
$myquery = mysql_query("TRUNCATE TABLE temp") or die("Error: ".mysql_error());
5) Ensure you are looking at the right place for the changes
You would be surprised how easy it is to get confused with multiple databases opened.
Double check the ip address of your DB server, your DB and table name and contents.
One of the above 5 steps will tell you what went wrong.
Please follow the following code. This will help you.
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$temptable = $_POST['temptable'];
$query = "truncate table $temptable";
if(mysql_query($query)){
echo "table empty";
} else{
echo "fail";
} ?>
Related
I built an html page with some options to insert details for a friends club.
I used an INSERT query and it worked. I want to add other queries like an UPDATE, DELETE, SELECT etc.
this is the php file:
<?php
//Input posted data.
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$Date = $_POST["Date"];
$Mail = $_POST["Mail"];
$Pass = $_POST["Pass"];
// Create connection
$conn = mysqli_connect('localhost','root',"");
//Check if the connection was opened, if not prompt the error to the page.
if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
//Select the data base.
mysqli_select_db($conn, "club");
//Set the character set to utf-8 to allow hebrew.
mysqli_query($conn, "SET NAMES 'utf8'");
//SQL query - user Details
$sql = "INSERT INTO customers (Fname, Lname, Mail, Date, Pass)
VALUES('$Fname','$Lname','$Mail','$Date','$Pass')";
//Run SQL query
$results = mysqli_query($conn, $sql) or die (mysqli_connect_errno());
//Close the SQL connection.
mysqli_close($conn);
?>
I want to use those queries in the same file.
how can I do that?
Should I add a new form on the same page?
For example <form name="input" action="Update.php" method="POST"> to direct it to the Update.php file?
can I use more than one form at the same html file?
I've created this form for the Update button on the page to Update.php file but it doesn't work. It just adds the details and does not update them, although I used the UPDATE query.
You take all your PHP code and put it in the head of the form's page, then wrap it all inside
if(isset($_POST['submit-button-name'])){
//YOUR PHP CODE
}
Now you for each submit-button-name you make an if statement with it, for example
if(isset($_POST['insert'])){
//YOUR INSERT QUERY
}
if(isset($_POST['update'])){
//YOUR UPDATE QUERY
}
if(isset($_POST['delete'])){
//YOUR DELETE QUERY
}
That if you for example have 3 buttons like the following
<button type='submit' name='insert'>INSERT</button>
<button type='submit' name='update'>UPDATE</button>
<button type='submit' name='delete'>DELETE</button>
Inside the form, of course the UPDATE & DELETE queries require an identifier to find the row
WHERE id = $id
So it depends how you will implement the buttons in one form.
on my research site, I have a few radio buttons and I want to send their values to MySQL table using jquery and AJAX. All buttons and jquery code are put in single-project.php (I modified WordPress theme) and the bits of code that should handle interaction with the MySQL are put in the db.php in the same folder.
However, something is not in order, because values do not appear on the database table. Could someone help?
jquery:
//the last button
$('#submit_last_button').click(function(){
SomeVariable = $('input:radio[name=lastRadio]:checked').val();
if (!$("input:radio[name=lastRadio]").is(":checked")) {
$("label#lastRadio_error").show();
$("input#lastRadio").focus();
return false;
} else {
if ('input:radio[name=lastRadio]:checked')
$('#PreviousButtonDiv').hide();
$('#NextDiv').show();
$.post('db.php',{action: "submit_last_button", previous_variable:SomePreviousVariable, last_variable:SomeVariable},function(res){
$('#result').html(res);
});
}
});
});
db.php:
<?php
$con = mysql_connect('localhost','user', 'password');
$db = mysql_select_db('my_database');
if($_POST['action'] == 'submit_last_button'){
$previous_variable = mysql_real_escape_string($_POST['previous_variable']);
$last_variable = mysql_real_escape_string($_POST['last_variable']);
$sql = "insert into MyTable (id, variable1, variable2) values ( NULL, '$previous_variable', '$last_variable')";
$query = mysql_query($sql);
if($query){
echo "Record Inserted.";
}else {
echo "Something Wrong!";
}
}
?>
There are various possibilities of what is not working on your code. But first, the problem is not in AJAX not saving on MySQL. AJAX is passing your data to the php script on your server to then, save it on MySQL.
Check if the values are reaching your script correctly;
Check if you're getting a db connection - check error logs or print them out;
Check if you're not getting a SQL syntax erro - again, check for logs;
Check if auto-commit is true (it is by default).
I would like to know how to make a text box for the user to type and then create a database named after this input.
<?php
/*
code to connect and make a mysql database named after the user input
*/
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action=<?php $_SERVER['PHP_SELF']; ?>>
<input type="text" name="databasename">
<input type="submit" name="submit">
</form>
</body>
</html>
It technically depends on the DBMS you use, but just make a SQL query (using MySQL) of "CREATE DATABASE databasename" would do it.
However, unless you're creating a database management tool like PhpMyAdmin, don't do this. You're just asking for users to run amok in your system.
And that's just the basics. I implore you to read the documentation on MySQL
You absolutely have to make sure the user's input is useable and not a hacking attempt or a mistake. So, first you check the input, and then if it's okay, you create a database.
This is assuming you add action="post" in the form. I don't like putting inputs into "get" because then your variable's part of the URL, and some people might try to set bookmarks with it there.
if(isset($_POST['databasename'])) { //this lets us know the form has posted
// 1. Check for acceptable name
$name = $_POST['databasename'];
$name = strtolower($name); //all lowercase (makes things easier to deal with)
$name = preg_replace("/[^a-z]/", '', $name); //get rid of things that aren't letters
if($name != '') {
// 2. Create the database
$mysqli = new mysqli('localhost', 'my_user', 'my_password');
if ($mysqli->connect_error) {
throw new Exception("Connect Error ($mysqli->connect_errno) $mysqli->connect_error");
}
$query = "CREATE DATABASE `$name`";
$mysqli->query($query);
if($mysqli->errno) {
throw new Exception("Error creating database: $mysqli->error");
// I am pretty sure this is enough to catch the error of the database already existing
}
echo "Database $name created.";
} else {
throw new Exception("Invalid name");
}
}
If I were you, I would put this in a try-catch to catch the exceptions and handle them.
As you haven't declared a method for your form it defaults to GET.
$db_name = $_GET['databasename'];
$host="localhost";
$user="username";
$password="pa55word";
$con=mysqli_connect($host,$user,$password);
// Create database
$query="CREATE DATABASE `$db_name`";
if (mysqli_query($con,$query))
{
echo "Database created";
}
else
{
echo "Error creating database...";
}
If the user isn't root though, you need to make sure you have granted the user enough privileges to create a database.
You can use this method to check if there exists a database with same name and through an error else create it and display created successfuly
<?php
if(isset($_POST['submit'])){ //check for the submit button pressed
$dbname=$_POST['db']; //store the database name in php variable
$query= mysqli_connect('localhost','root','')or die("Error establishing connection"); //check for database connectivity
$a="CREATE DATABASE IF NOT EXISTS ".$dbname; //create a database if it doesn't already exist
$q= mysqli_query($query, $a) or die("Database already exist.. please try different name");
echo "Your database ".$dbname." is successfully created";
}
?>
for the html form refer the code below:-
<form method="post" action="">
Enter database name: <input type="text" name="db" /><br/>
<input type="submit" name="submit" value="submit"/>
</form>
Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.
I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>
Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());
store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());