PHP code just prints on screen instead of running [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
For some reason I can't connect to database. Here's my code:
<?php
//only process form if $_POST isnt empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'username', 'password', 'database' );
//Check connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli- >connect_error );
}
//Insert form data
$sql = "INSERT INTO user ( Name, Username, Password, Email ) VALUES
( '{mysqli->real_escape_string($_POST['Name'])}',
('{mysqli->real_escape_string($_POST['Lastname'])}',
('{mysqli->real_escape_string($_POST['Username'])}',
('{mysqli->real_escape_string($_POST['Password'])}' )
('{mysqli->real_escape_string($_POST['Email'])}' )";
//Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
}else{
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
//Close our connection
$mysqli->close();
}
?>

Warning: your code is susceptible to SQL Injection!
Never use $_POST[] or any user submitted data directly in a SQL Insert.
Use Prepared Statements instead!
Regarding the code just prints on the screen:
If the PHP Code is printing on to the screen instead of being interpreted by the server; first make sure that the PHP file is using a valid PHP extension such as .php and not just .html
Also make sure that the php module is installed for your web server (this would be different instructions for IIS then for Apache).
Also your code is missing the actual query itself which is done using the following code:
$insert = $mysqli->query($sql) // do the insert
Then the rest of your code will start to function:
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
}else{
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
Without the $mysqli->query($sql) your hitting the else and die()
See query for more info.

The sql should be executed to return a result $insert
Example: $insert = $mysqli->query($sql)
(And, as mentioned it's much safer to use prepared statements.)

well, you wrote
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
That echoes exactly what is between the subsequent quotation marks (as a string)...

The script will keep hitting the die statement because $insert hasn't been set. So you are right: it just prints to the screen.
When you copied and pasted the code from "The Internet" you forgot one line - as Philip pointed out:
$insert = $mysqli->query($sql)
Without it, the only thing that your script would do is create a connection and close it again - or, most likely: not even managing to close it because it would die before it reached that line. :)
The line you forgot is supposed to be inserted just after the $sql string but before the conditional using $insert.

Related

Delete row(s) with respect to username [duplicate]

This question already has answers here:
delete using where and or
(4 answers)
Closed 4 years ago.
i've gone through most of the questions similar to this but none addressed my problem.
i have table with four columns : id,username,title and date. i want to delete the entire row(s) associated with a specific username when the user clicks a button (anchor tag). pls, how do i achieve this? heres the code i tried.
php
<?php
session_start();
$uname = $_SESSION['username'];
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
die("Connection failed:". mysqli_connect_error($dbconn));
}
if($stmt = $dbconn->prepare("DELETE * FROM notes_log where username = ? ")){
$stmt->bind_param("s",$uname);
$stmt->execute();
$stmt->close();
}else{
echo "ERROR: could not prepare SQL statement.";
}
mysqli_close();
// redirect user after delete is successful
header("Location: index.php");
?>
HTML
Delete all
The above code redirected the page but nothing was deleted.
Get rid of the * in the query. The syntax is just:
DELETE FROM notes_log where username = ?
See DELETE Syntax.
In a multi-table DELETE you need to put the table names after DELETE, but a single-table DELETE should have nothing there.
And when an SQL operation fails, you should print the SQL error message, not just could not prepare SQL statement, e.g.
echo "ERROR: could not prepare SQL statement: " . $dbconn->error;
Edit: mysqli_close() requires a database connection as its only argument.
Ref: http://php.net/manual/en/mysqli.close.php
You will need to use mysqli_close($dbconn).

Delete function is not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am doing a system with php code,But delete function with SQL is not working.I don't know why it happens.
Below is my code:
function deleteEmployee($params)
{
$tid = $_SESSION['tmid'];
$data = array();
//print_R($_POST);die;
$sql = "delete from `cusinfo` WHERE TICKET_ID='".$params["id"]."' AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = '$tid')";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
The problem probably is in the line echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
As I said in one comment, replacing the die string with mysqli_error($this->conn) should display an error.
However after some testing I found that assigning a variable in a echo might give strange results, i test echo $test = "hello" or die("test"); and found that neither hello nor test was displayed on the screen, but 1 was displayed, which probably was the boolean true.
A better way to see if the query was executed could be:
//other code that stayed the same
$statement = mysqli_prepare($this->conn, "delete from `cusinfo` WHERE TICKET_ID=? AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = ?)");
$statement = mysqli_stmt_bind_param($this->conn, $params['id'], $tid); //
$sql = msyqli_stmt_execute($statement); // returns either true or false
if ($sql === true) {
echo "Successfull"; // executing successfull code
}
else {
var_dump(mysqli_stmt_error_list($statement)); // handling error
die;
}
This will handle some sql errors in a way that is expected(they are 'dumped and died').
Using prepared statements the correct way will mean that most sql injections are able to be stopped, and with a DELETE query, you want to make sure that sql injections are stopped.
Note: I am no expert on sql injections
Note 2: I would have used PDO for prepared statements though, it seems to me to be much more logical to work with
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
In above line you are execution query and echo it. But if it is not executed you are echo your own message. This will prevent you from actual error message. And if the row that you are going to delete from TICKET_ID not exsist you cannot see it, you only see your message "error to delete employee data".
To solve this:
echo mysqli_error($this->conn);
This will give you connection error.
Or:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
Many many function have to handle these errors. stackoverflow question, php manual and this.

PHP Error with syntax : "check the manual that corresponds to your MariaDB server version for the right syntax " [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Error: INSERT INTO reservations (GameID,Name,Numberofdays,ReservationID,Startdate)VALUES (5,'jp', 4, ,'2016-03-23')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2016-03-23')' at line 30 results
The code bellow does insert the information that is inputted from a form even though the SQL query is correct . I have tested and changed the code many times and have discussed and reviewed it with my peers .
Bellow is the code for it :
<div id="content">
<?php
//variables needed to connect to the database
$user_name = "root";
$password = "";
$database = "game_library";
$host_name ="localhost";
// Create connection
$con=mysqli_connect($host_name,$user_name,$password,$database) or die("Error ");
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//link the search term to the html page
$GameID=$_POST['GameID'];
$Name=$_POST['Name'];
$Numberofdays=$_POST['Numberofdays'];
$Startdate=$_POST['Startdate'];
//sql query to add the data from the form elements to the sql database
//The reservationID is auto incremented so requires a space
$qry_reserve = "INSERT INTO reservations
(GameID,Name,Numberofdays,ReservationID,Startdate)VALUES ($GameID,'$Name',
$Numberofdays, ,'$Startdate')";
//Runs the query if the database if connection succesful
if ($con->query($qry_reserve) === TRUE) {
echo '<br/>';
echo $Name. ' has been added successfully</h2>';
echo '<hr>';
} else {
echo "Error: " . $qry_reserve . "<br>" . $con->error;
}
//show added data & all records to prove they have been added. You don't have to do this
$qry_show_table = "SELECT * FROM reservations WHERE GameID='$GameID' ";
$result = mysqli_query($con, $qry_show_table);
if (mysqli_num_rows($result) > 0) { // checks if there are more than zero rows returned.
// output data of each row
while($row = mysqli_fetch_assoc($result)) //puts all the results into an associative array that we can loop through
{
echo '<br/>';
echo 'Name: '.$row['Name'];
echo '<br/> GameID: '.$row['GameID'];
echo '<br/> Startdate: '.$row['Startdate'];
echo '<br/> Numberofdays: '.$row['Numberofdays'];
echo '<br/>';
echo '<hr>';
}
} else {
echo "0 results";
}
$con->close();
?>
Leave out the parentheses:
INSERT INTO reservations
VALUES ($GameID, '$Name', $Numberofdays, ??,' $Startdate')
---------------------------------------------^ something needs to go here
Or, better yet, list the columns:
INSERT INTO reservations(col1, col2, col3, col4, col5)
VALUES ($GameID, '$Name', $Numberofdays, ??, '$Startdate')
---------------------------------------------^ something needs to go here
Note that you have two commas with no value in between. Perhaps this is a typo, perhaps you intend NULL or DEFAULT or something else.
You won't need the parenthesis and also you have a extra comma:
$qry_reserve = "INSERT INTO reservations VALUES ($GameID,'$Name',$Numberofdays,'$Startdate'";
More information at http://www.w3schools.com/sql/sql_insert.asp.

php inserting into a MySQL data field

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Simple PHP code for using multiple foreign keys [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to code an order process. I have 3 different tables (orders, product, users) in a single database (dbphesemaas).
What I've tried so far doesn't work:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
mysql_close();
?>
Can someone make this code work, the id is a foreign key from users, while the product_id is a foreign key of product?
1. Error handling
You just connect and execute the query.
Well yeah nope - how are you making sure that everything worked?
Let's start off with error handling.
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
?>
Is the connection working? Did the database get selected successfully?
You can use the if module to check if it worked.
<?php
// IF $link = mysql_connect('localhost', 'root', '') did not work (note the ! in front of it)
if(!$link = mysql_connect('localhost', 'root', '')){
die('Could not connect to localhost'); // The message displayed. die() will prevent the rest of the script from executing.
}
// IF database "dbphesemaas" did not get selected succesfully (note the ! in front of it)
if(!mysql_select_db('dbphesemaas', $link)){
die('Could not select the database "dbphesemaas"'); // The message displayed. die() will prevent the rest of the script from executing.
}
?>
Now we have the connection working. If something goes wrong, the script will stop being executed and throw a custom error.
2. Unnecessary variables
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
Now is my question, why? There is nothing wrong with just using them inside the query. The only reason why you only would make variables is if the old variable is very long (so the chance of typo's are bigger) and/or if the code is too messy in your opinion. Since there is no problem in this code to use the $_POST variable, we're going to scratch this piece of code.
3. The actual query
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
There are a few problems here:
You wrote the query, but you aren't executing it.
You are using variables ($id, $id2 etc) inside quotes. In the wrong scenario, it's gonna insert $id in the database instead of the actual value.
Once again, no error handling.
No untainting at all. The user can add on into your query and alter the query, making a possible leak and the chance of being hacked bigger. We're going to prevent this with mysql_real_escape_string: http://php.net/manual/en/function.mysql-real-escape-string.php
Looks kinda messy, but that's just a visual problem.
Let's fix these problems:
$query="
INSERT INTO
orders
(
id,
product_id,
address,
quantity
)
VALUES
(
'". mysql_real_escape_string($_POST['id']) ."',
'". mysql_real_escape_string($_POST['id2']) ."',
'". mysql_real_escape_string($_POST['adress']) ."',
'". mysql_real_escape_string($_POST['quantity']) ."'
)
";
if(mysql_query($query)){
echo 'Succesfully executed the query.';
}
else
{
echo 'Query not executed - MySQL error. <br>';
echo '<pre>'. mysql_error() .'</pre>';
}
Using '". (random php code) ."' allows php code to be executed within a string. For example:
$variable = 'This is text '. strtoupper('this is capitalized since strtoupper makes this capital. note that this is inside the string.') .' and this is once again lowercase.';
4. Keep this for the future
The way I wrote these codes are useful for the future. Keep the use tabs every time you open/add a new bracket ({).
Further info - the default mysql_* functions are going to be deprecated as of PHP 5.5 - Use MySQLi in the future, it's the improved version. Info: http://www.php.net/manual/en/book.mysqli.php
5. For your actual problem
One mysql_query can only execute one query. You can do this:
$queries = array();
$errors = array();
$queries[] = 'INSERT INTO ... '; // using $variable[] will add another entry to the $variable array.
$queries[] = 'INSERT INTO ... ';
$queries[] = 'UPDATE bla SET ...';
foreach($queries as $query){
// Foreach will seperate the entries in an array
// IF mysql query failed
if(!mysql_query($query)){
$errors[] = mysql_error(); // We'll add the errors to an array aswell.
}
}
// Check if there are entries in the $failures array.
if(count($errors) > 0){
echo 'We had some MySQL errors.';
echo '<ul>';
foreach($errors as $failure){
echo '<li>'. $failure .'</li>';
}
echo '</ul>';
}
else
{
echo 'No errors - MySQL queries executed succesfully.';
}
Hope this helps you on your way.

Categories