mysqli insert execute twice - php

I have 2 files, file number is the connection, it look like this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName= "abc";
// Create connection
$db = new mysqli($servername, $username, $password, $dbName);
?>
then the second file, where I include the first one, look like this
include '../db.php';
$stmt = $db->prepare("INSERT INTO test(a,b,c,d,e) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssis', $a,$b,$c,$d,$e);
$stmt->execute();
$stmt->close();
Why does it execute twice when I run the second file? does it cause by the include of the first file?

You must be running the execute twice for sure. It is not visible from this code why it happened twice, page refresh is good candidate.
Add some debugging output to understand what causes this part of code to be run twice.

In addition to Margus' answer... Is it possible that you are including the second file twice? That would also cause that to happen. You need to be sure that this file is only being run once.

Related

Php redirct each data to each url

I have a database where I am storing data. Here every full link has a offer link. What I am trying to do? I want to redirect every single data to every different URL. But I failed.
Example:1
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fgoogle.com
redirect link: google.com
Example 2
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fyoutube.com
redirect link: youtube.com
Someone when visiting the full link it should redirect each offer link
Database
Data Insert
PHP Code
You should really post code instead of images. You can post code blocks by posting your code between 3 backticks (`) at the top, and three backticks at the bottom.
However, I tried to copy the code, and edited it. I don’t understand exactly what you are trying to do, but I just made some changes.
Data Insert
<?php
include 'db.php’;
$first = "http://localhost/LearnPHP/test/short2.php/redir&q=";
$magic = urlencode($_POST["longUrl"]);
if($magic) {
$finalUrl = $first . $magic;
$stmt = $conn->prepare("INSERT INTO url (offer_link, full_link) VALUES (?, ?)");
$stmt->bind_param("ss", $magic, $finalUrl);
$stmt->execute();
} else {
$finalUrl = '';
}
?>
In the above code, you can obviously tell I changed some things. First, I don’t have a checking statement inside the insert file. I have put it directly inside of the db.php file. I will post the code for it.
Next, I patched the vulnerability of mySQL injection (https://portswigger.net/web-security/sql-injection) using prepared statements.
db.php
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
For the last bit, can you please tell me exactly what you need to do? Your post isn’t that helpful. Do you want to use $_GET[‘’] for the redirection? Please edit your code. Read this as well: https://stackoverflow.com/help/how-to-ask
For redirection part you can do something like this:
if(isset($_GET['q'])) // if q param available
{
$redirectUrl = urldecode($_GET['q']); // get link
header("Location: $redirectUrl"); // redirect
}
I think that your problem is related to URL decode / encode: LINK

Is it necessary to close prepared statement in php [duplicate]

This question already has answers here:
When to close Prepared Statement
(2 answers)
When to call mysqli::close
(4 answers)
Closed 1 year ago.
Is it necessary to close the prepared statement in php by using $stmt->close();
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
php_mysqli library was written in low level languages which requires manual memory management. Whenever you allocate a new resource it takes some memory from the device RAM to host the allocated data.
Closing allocated resource free's that memory that later could be again used for another allocation requests or lets Operation System to give that part of memory to another programs when needed.
In short: if you want to make your code memory efficient you might want to close resources you've allocated previously. If you don't really care about the efficiency you might not close the resources.
Another think to keep in mind that Operation System also frees allocated memory chunks whenever a program completes execution. So, closing resources manually might not make a noticable improvement in some situations.
References:
C Memory Management - MIT
mysqli_stmt::close - PHP

Data entered through html form is not storing in database of phpmyadmin [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 2 years ago.
Improve this question
I'm just trying to store the integer (with id as id) that is entered by the user through html form, in database of phpmyadmin using php and mysql . I'm new to mysql and php. I'm sure that something wrong with the database connection code of php only or mysql queries. Database name is testdb and the table name is testdbtable.
My code is below.
<?php
if (isset($_POST['id'])) {
$integ = $_POST['id'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testdbtable (id)
VALUES ('$integ')";
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE TEST2</title>
</head>
<body>
<form method="post">
<label >Enter your integer:</label>
<input type="number" id="id" name="id">
<br>
<br>
<button type="submit">Submit</button>
</form>
You're defining the query but never run it.
Try this:
$sql = "INSERT INTO testdbtable (id) VALUES ('$integ')";
$conn->query($sql);
As Paul T. said, move the } to the end of the script. Otherwise, even if condition is false, You will just prevent definig $integ, but still running all the rest of the code.
Also, user Prepared Statements to make it more secure.
if (isset($_POST['id'])) {
$integ = $_POST['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Use prepared statements to make it more secure
$sql = "INSERT INTO testdbtable (id) VALUES (?)";
// Prepare statement and bind params
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $integ);
// Execute statement
$stmt->execute();
$conn->close();
}
Take a look at Should we ever check for mysqli_connect() errors manually? as #Dharman commented to stop manually error checking.
Before
$conn->close();
you need to run
$conn->query($sql);
This will actually execute the query.
But this is not the end of the story. You have other issues:
Your code is vulnerable to SQL injection attack. Consider changing the line:
$integ = $_POST['id'];
to
$integ = (int)$_POST['id'];
or (better!) learn how to work with prepared statements.
The query will still be invalid. I bet that the datatype of the column "id" in the "testdbtable" is INT and therefore you should not put quotes around its value. So the $sql variable should be:
$sql = "INSERT INTO testdbtable (id) VALUES ($integ)";
And one more thing - move all query-related code inside the if statement. You should not execute the query if the POST variable is not set.
Your <form> tag has no "action" attribute. You should include it so it do an actual post...

MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine

MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.

Prepared statements using MySQL not inserting POST values to database table

I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}

Categories