PHP - Write To MySQL Database - php

I'm simply writing some values to a MySQL database using the following snippets of code.
Please note, when I run SELECT queries, information is correctly displayed using echo etc.
However when I try to write to the database using INSERT, the code executes with no errors, but when I check my database there is nothing written to it.
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'xyz', '123', 'testdb');
$this->db->autocommit(FALSE);
if (isset($_POST["ID"]) && isset($_POST["Number"]) && isset($_POST["Address"]) && isset($_POST["Ticket"])) {
$id= $_POST["ID"];
$number= $_POST["Number"];
$address= $_POST["Address"];
$ticket= $_POST["Ticket"];
$stmt = $this->db->prepare("INSERT INTO tickets (ID, Number, Address, Ticket) VALUES (?,?,?,?)");
$stmt->bind_param("iiss", $id, $number, $address, $ticket);
$stmt->execute();
$stmt->close()
return true
}
Any help would be greatly appreciated.
Edit
Question - Could it be something to do with write access to the database? I've checked the user account privileges and it has all privileges.

When using the insert auto_commit must be TRUE.
$this->db->autocommit(TRUE);

You've disabled autocommitting ($this->db->autocommit(FALSE);), and you're not committing anywhere explicitly. Once you close the connection, anything you inserted will be rollbacked, as if you never changed the database. Once you're done inserting, you should add a call to $this->db->commit().

Related

How to fix mysqli updating wrong value in db?

I'm setting up a password change script for php. All variables are in the function updatePasswordInDatabase($password, $email) { ..}.
I've triple checked that the values that the function receives are correct.
For the insertion in the database (mysql) i'm using mysqli with prepared statements.
For example, I'm inputting:
$2y$12$X/jIjlqpWfSSMg70u0RE8O0VWH3ocqychlUPy7CSG2vMhkj/F5d.q
(as $password) along with:
test#test.com ($email).
I get those values in the function correctly.
However after the update, i'm getting a different value in the password column:
i1VjH4sRf5nqv3tnShnXNTSX57jRGnbZJt7w0VLX49nZdKRsRT
What am I doing wrong?
Thanks
function updatePasswordInDatabase($password, $email) {
require $mysql;
$stmt = $conn->prepare('UPDATE `users` SET Password = ? WHERE Email = ?');
$stmt->bind_param("ss", $password, $email);
$stmt->execute();
}

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

PHP PDO select entry from database that matches a variable

I've looked at some of the other answers on here regarding this but I keep getting errors so here goes.
Whenver a user visits the site, they are asked to provide their name and are assigned a random integer. When they hit submit to enter their name the form gets submitted and saved to the database and the user gets redirected back to the main page. If the random number once again matches a number saved in the database, that name gets displayed.
I have no problem inserting values into the database but I am having some issues retrieving them back out.
My connection to the database is fine, just left the values generic for the purpose of this question.
<?php
$min=1;
$max=100;
$rand_number = rand($min,$max);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//Set PDO Error Mode to Exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL
$stmt = $conn->prepare("select nickname from users where number=".$rand_number);
$stmt->execute();
if (!$stmt) {
foreach($result as $row) {
echo $row['nickname'];
}
}
}
?>
I'm getting an error that something is wrong around the part where I'm matching the query to the variable.
The only thing I really see missing is where you would fetch the data. You can either use one of the fetch* methods of PDOStatement or simply iterate the statement itself (it implements Traversable).
Also, you should use parameter binding.
$stmt = $conn->prepare('SELECT `nickname` FROM `users` WHERE `number` = ?');
$stmt->execute([$rand_number]);
while($nickname = $stmt->fetchColumn()) {
echo $nickname;
}

php mysqli FRUSTRATION

I have to following code:
session_start();
if(isset($_SESSION['Username']))
{
//User has selected auto sign-in re-fill session variables.
$mysqli = new mysqli('****','****','****','****');
if($mysqli->errno)
{
//Error connecting
}
else
{
//No error connecting to database
$stmt = $mysqli->prepare("SELECT Expires FROM Subscribers WHERE UName=?");
$stmt->bind_param('s', $_SESSION['Username']);
$stmt->execute();
$stmt->bind_result($Expires);
$stmt->store_result();
while($row = $stmt->fetch())
{
if($Expires < time())
{
//Deny user
$pageToShow = "Payment";
}
else
{
//Accept
$pageToShow = "Content";
}
}
}
}
else
{ ... }
I am getting the error Fatal error: Call to a member function bind_param() on a non-object in /home/content/42/7401242/html/****/wp-content/themes/****/archive.php on line 15
I just had an error like this about 30min ago on a different page, and I had for gotten the FROM from the sql query, but I have read, re-read, re-checked, every single letter of the code, over and over. I am about to pull all of my hair out...
What am I doing wrong?
That's simple.
You're not handling errors.
And not even asking how to do that.
In your other question they showed you error itself instead of showing you the way how can you see the error yourself.
In the present question the answer is "check your query" which is not too helpful too.
Instead of asking other people to find typos in your queries, you have to ask mysqli to do that. That's way more efficient, especially because there could be another mistake, not in the query but somewhere else.
So, you have to check every database interaction result and translate it into PHP error.
$sql = "SELECT Expires FROM Subscribers WHERE UName=?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error);
...
$stmt->execute() or trigger_error($mysqli->error);
so, you will immediately know what's going wrong.
The error tells you that your SQL query is returning an empty result.
two things you must do:
check that you are connected to the database properly and that you
have the permissions to access the data in the database
check your query and see if it returns any results in your SQL
database.

updation of table through php mysql

This is my code to update a table. My problem is that after submitting a fresh record I'm unable to update the first time (it shows blank), but the second time it works fine.
One more thing: when I remove the include statement then it is working fine on submessage.php there is no any phpcode. [annakata: I have no idea what this means]
$pid = $_GET['id'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$content = $_POST['content'];
$catid = $_POST['cid'];
$author = $_POST['author'];
$keyword = $_POST['keyword'];
$result1= mysql_query("update listing set catid='$catid',title='$title',
summary='$summary',content='$content', author='$author', keyword='$keyword' where pid='$pid'",$db);
include("submessage.php");
The things that are wrong with that piece of code are hard to enumerate. However, at the very least, you should establish a connection to the database before you can query it.
Why not just redirect to submessage.php rather than inlining it? Redirecting also prevents duplicate db operations when user refreshed the page. Just replace include statement with:
header('Location: submessage.php?id=' . $pid);
die();
Also, before you deploy your application: DO NOT EVER PUT USER INPUT DIRECTLY IN SQL QUERY. You should used bound parameters instead. Otherwise, you could just as well publicly advertise your database admin password. Read more on PDO and prepared statements at http://ie.php.net/pdo
Here's how I would do it:
$pdo = new PDO(....); // some configuration parameters needed
$sql = "
UPDATE listing SET
catid=:catid, title=:title, summary=:summary,
content=:content, author=:author, keyword=:keyword
WHERE pid=:pid
";
$stmt = $pdo->prepare($sql);
$stmt->bindValue('catid', $_POST['catid']);
$stmt->bindValue('title', $_POST['title']);
$stmt->bindValue('summary', $_POST['summary']);
$stmt->bindValue('content', $_POST['content']);
$stmt->bindValue('author', $_POST['author']);
$stmt->bindValue('keyword', $_POST['keyword']);
$stmt->bindValue('pid', $pid = $_GET['id']);
$stmt->execute();
header('Location: submessage.php?id=' . $pid);
die();
Or in fact, I would use some ORM solution to make it look more like that:
$listing = Listing::getById($pid = $_GET['id']);
$listing->populate($_POST);
$listing->save();
header('Location: submessage.php?id=' . $pid);
die();
Other than the usual warnings of SQL injection - very likely given your code and where you're obtaining the query parameters from (sans any kind of validation) - then it's quite possible your problem has nothing to do with the queries, particularly if it's working on subsequent attempts. Are you sure $_GET['id'] is set the first time you call the script?
Just to note, there is absolutely no reason to have to perform several update queries for each field you need to update - just combine them into a single query.

Categories