Transaction is not working - PHP and MySql - php

I'm beginner to PHP transaction concept. My code is not working. I don't know what is my mistake. Anyone help me to find out my mistake.
My first query is wrong one. It didn't work. Second is successfully executed. If I have checked by IF condition, My control successfully moved to else part. It's fine. But My rollback function not working. Second query date will be present in table.
What is my mistake?
<?php
$link = mysqli_connect("localhost", "root", "", "hrms_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Transaction start */
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
/* disable autocommit */
mysqli_autocommit($link, FALSE);
$result1 = mysqli_query($link, "INSERT INTO EmployeeBackup (Name, OfficialEmail, Department, Manager_ID, MobileNO, Status, Location, full_name) value ('s', 's', '1' , '3', '5', '4', '5' , '78')");
$result2 = mysqli_query($link, "INSERT INTO hrms_general_master (lookup_type, lookup_description) value ('Testing', 'Testing')" );
if($result1 && $result2){
/* commit insert */
mysqli_commit($link);
echo "All queries were executed successfully";
} else{
/* Rollback */
mysqli_rollback($link);
echo "All queries were rolled back";
}
mysqli_close($link);
?>
Then please explain different type of parameter used in mysqli_begin_transaction and use of it. I have little more doubt in mysqli_begin_transaction and mysqli_commit. Please clarify my doubt.
Thank you.

You need the InnoDB access method to use transactions. The people who created MyISAM did not include transactions in their code.
Plenty of tutorials on the net explain DBMS transactions in general, and MySQL transactions in particular. Here is just one.
http://www.tutorialspoint.com/mysql/mysql-transactions.htm

Related

Can't get simple Object oriented row count to display

Been struggling with this for two days (and the rest). Read a couple of dozen posts from this site, been reading lots from w3 schools and lots of other resources online.
All I'm trying to do is show how many people have signed a petition.
After many failures, I wiped what I had and started from scratch.
I tried a few bits of code from w3 to check my connection to my database. The PDO didn't work at all, but object oriented worked fine. (Showed "connection successful" on my page.)
So then tried the code below, which I took from the PHP manual and still can't get it to work.
Would really appreciate some help.
<?php
$link = mysqli_connect("localhost", "my user", "my password", "my db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT Code, Name FROM 'wp_rm_submissions' ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
printf("So far %d people have signed the petition.\n", $row_cnt);
/* close result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
I've also tried it without the single quotes around the table name.
My website is here.
It's a WordPress site, if that matters.
If you only need to count the records use select count:
SELECT count(Code) as count FROM wp_rm_submissions
This query will return a resultset with one record, the record will have a field called count and it's value will be the number of records stored in the wp_rm_submissions table.
A very very very simple example in php, using mysqli, would be:
<?php
// connect to mysql
$mysqli = new mysqli('host','user','password','schema');
// execute the query
$result = $mysqli->query('SELECT count(Code) as count FROM wp_rm_submissions');
// fetch the record as an associative array
$record = $result->fetch_assoc();
// get the value
$count = (int)$record['count'];
$mysqli->close();
printf("So far %d people have signed the petition.\n", $count);

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);

Write to MYSQL table not working

I am trying to write to a MySQL Database / Table with the following code - but for some reason it just won't write! I've changed the "INSERT INTO" line quite a few times, trying different things each time - no luck!!!
The DBsettings.php contains variables with the MySQL connection info - which worked for creating the tables and setting the column types and stuff. For your information, it is running the main code (there are no errors with the user info entered), and echoing "Awesome! No errors!", so I'm not too sure what's not working - the MySQL checking line is saying that I'm able to connect properly... Can someone look over my code?
The PasswordHash.php file contains code for hashing and salting passwords - nothing to see here, got it from another site, no errors at all.
I know I'm not 'cleansing' the MySQL code for more security...
if($error == null){
include('DBsettings.php');
$connect = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL Database! Error: '.mysqli_connect_error();
} else {
include('PasswordHash.php');
$passinfo = explode(':', create_hash($password));
$addinfo = "INSERT INTO {$dbprefix}Users (Email, Displayname, Registered, Rank, Status, Password, Salt) VALUES ('{$email}', '{$displayname}', '{date('Y\/m\/d')}', 9999, 1, '{$passinfo[3]}', '{$passinfo[2]}')";
/* format: algorithm:iterations:salt:hash */
mysqli_query($connect, $addinfo);
mysqli_close($connect);
echo 'Salt: '.$passinfo[2];
echo '<br>Hash: '.$passinfo[3];
echo '<br>Awesome! No Errors!';
}
} else {
echo $error;
}
That's the code in question - I've tried adding;
error_reporting(E_ALL);
ini_set('display_errors', '1');
But all that reveals is undefined localhost errors in my DBsettings.php file - and the file worked when I created the MySQL DB tables, so I don't really have that as a priority.
Thanks!
If you echo your query, you will notice this issue. Following is your final query
INSERT INTO Users (Email, Displayname, Registered, Rank,Status, Password, Salt)
VALUES ('', '', '{date('Y\/m\/d')}', 9999, 1, '', '')
Notice that your date was not interpolated like you expected it to, and i'm sure if you have that field in MySQL set as a datetime field, it wont accept that value {date('Y\/m\/d')}, Move the date function call outside the string.
Plus you are not getting any error after the query execution because you are simply not checking for one. One example how to check for that can be
if (!mysqli_query($connect, $addinfo)) {
printf("Error: %s\n", mysqli_error($connect));
}
I saw your INSERT query contains this '{date('Y/m/d')}' ,maybe the single quotes has conflict,You'd better escaping the date('Y/m/d') statement's single quotes.

Database cannot create a record when a text value is entered ($_POST)

Perhaps I'm making some obvious beginner mistake, but I just cannot seem to figure out why this happens.
Strangely enough, the code only seems to work properly if I enter a number into the "inputbox". I check this in the myphpadmin panel, and it shows a new record has been created. However, if I attempt to input a string as intended for my purposes (example: "hello") no new record appears in the database...
In short, the database only updates if I put a number into the "inputbox" but not when I enter a string.
Any ideas why this may be happening? It's driving me crazy. If it helps, the data type of the "Company" field is VARCHAR and the collation is set to latin1_swedish_ci
The PHP code is as follows:
<?php
//Retrieve data from 'inputbox' textbox
if (isset($_POST['submitbutton']))
{
$comprating = $_POST['inputbox'];
//Create connection
$con = mysqli_connect("localhost","root","","test_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert data into 'Ratings' table
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ($comprating,1)");
mysqli_close($con);
}
?>
The HTML code is:
<form method="post">
<input type="text" name="inputbox">
<input type="submit" name="submitbutton">
</form>
Cheers
Try this query,
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ('$comprating',1)");`
^ ^
Note the single quotes that reserves the string value and don't forget to sanitize the input before inserting them to database.
Sample standard escaping:
$comprating = mysqli_real_escape_string($comprating) before executing a query that uses $comprating
Hi here is the objected oriented method and also its secure because data binding is used in mysqli. I recommend to use this.
if (isset($_POST['submitbutton'])) {
$comprating = $_POST['inputbox'];
$mysqli = new mysqli("localhost", "root", "", "test_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO Ratings (Company,Score) VALUES (?, ?)");
$stmt->bind_param($comprating, 1);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$mysqli->close();
}
feel free to ask any questions if you have..

mysqli migration issue and security advices

I tried to migrate from mysql to mysqli but this code doesn't work. I'm new to php and mysql
$link = mysqli_connect("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n",
mysqli_connect_error()); exit(); }
if ($result = mysqli_query($link, "SELECT * FROM users WHERE uid='$uid'")) {
if(mysqli_num_rows($result) != 0) {
mysqli_query($link, "UPDATE users SET array='$array' WHERE uid='$uid'");
}
else {mysqli_query($link, "INSERT INTO users (uid,array) VALUES ('$uid','$array')"); }
mysqli_free_result($result); }
/* close connection */
mysqli_close($link);
?>
So my questions are:
what should be changed to make this code work;
what security vulnerabilities does this code have and what changes in the code would you suggest to fix that?
Thanks for spending time to answer my questions.
You need to set error reporting to maximum level and make error messages available. this way you will let PHP to tell you what is going wrong and what needs to be fixed.
however, sometimes our code still doesn't work yet there are no error messages around. it's time to do some debugging
You have to change this code to make every variable to go into query via placeholder only
however, raw mysqli is extremely bad with prepared statements, so, I would recommend not to use it but rather move toward PDO or safeMysql. A latter one will let you to have safe queries with the same amount of code.
if ($db->getOne("SELECT 1 FROM users WHERE uid=?i",$uid))
{
$db->query("UPDATE users SET array=?s WHERE uid=?i",$array,$uid);
} else {
$db->query("INSERT INTO users (uid,array) VALUES (?i,?s)",$uid,$array);
}
By the way, Mysql lets you to make all these three queries in one:
$sql = "INSERT INTO users (uid, array) VALUES (?i,?s)
ON DUPLICATE KEY UPDATE array=values(array)";
$db->query($sql, $uid, $array);

Categories