PHP - About Begin, Commit And Rollback In Core Php Mysqli
In my one php registration form i have generated one code automatically and if multiple users registering on form then each registration should be on different code but right now its not working. Right now if only two users using same form, still it is registering same code for two records. Please tell me how to make it perfect for multiple users??? Following i am sharing my core php code, Please tell me whether it is correct or wrong and tell me the changes also:
<?php
// Insert
// Insert Query
$DB_Error = "Database Error => ".mysqli_error($dbCon); ?>
<script type="text/javascript">
Similar TutorialsI am new to MySQLI and tried to test the rollback functionality. I created a simple database called mysqli and one table called test with and id and name field. my PHP is as follows: Code: [Select] $mysqli = new mysqli('localhost',name,password,'mysqli'); $mysqli->autocommit(FALSE); $result = $mysqli->query("INSERT INTO test (name) VALUES('bla')"); $mysqli->commit(); $mysqli->rollback(); After hitting the page, it does the insert, but does not roll back the transaction. So it ends up being inserted into the DB. Why is the rollback not working? Hello , this is my first post in this forum , i would like to see the following code and tell me your opinion , not about the security issues not about how good or bad it is. Its just a simple demonstration in order to show you the problem.
<?php include('config/functions.php'); $mysqli = connectionToDb(); $mysqli->autocommit(FALSE); $stmt = $mysqli->prepare("INSERT INTO users (first_name,last_name) VALUES ('stelios','stelios2')"); $stmt->execute(); $stmt->close(); $stmt = $mysqli->prepare("INSERT INTO users (first_name,last_name) VALUES ('stelios3','stelios4')"); $stmt->execute(); $stmt->close(); var_dump($mysqli->commit()); $mysqli->close();This is the code and the var_dump($mysqli->commit()); line prints false ! BUT , the inserts are in the database. If i comment out the commit line , then nothing is in the database. Can you advise ? Thanks !
Hi folks, I'll try my best to explain my problem... hopefully someone can shed some light on this... Essentially, I've written a "database wrapper" to handle any DB requests (selects, inserts, etc). It's using PDO... At some point in my dbwrapper, I create a wrapperStatement object, passing along by reference, the PDO connection. After creating this wrapperStatement object, I call a function within it that'll do multiple inserts....
On my NAS, this multiInserts() function seems to be cause a 500 http server error. When I tried running the same script, directly on the server's command line with php-cgi, I get a Segmentation Fault.
HOWEVER, I've installed PHP and Lighttpd on my working PC, and the code in multiInserts() just works ! class dbwrapper { ... $con = &$this->getConnection(); $dbwrapperStmnt = new wrapperStatement($con) $dbwrapperStmnt->multiInserts(); ... } class wrapperStatement { private $_conn; public function __construct(&$conn){ $this->_conn = &$conn; } public function multiInserts(){ // init data $data = array ( array ( "jdoe1", "jdoe1@email.ca", "abc1"), array ( "jdoe2", "jdoe2@email.ca", "abc2"), array ( "jdoe3", "jdoe3@email.ca", "abc3"), array ( "jdoe4", "jdoe4@email.ca", "abc4"), array ( "jdoe5", "jdoe5@email.ca", "abc5"), ); // init variables $username = null; $email = null; $passwd = null; $sql = "INSERT INTO users (USERNAME, EMAIL, PASSWD) VALUES (:username, :email, :passwd)"; try { $con = new PDO("mysql:dbname=somedb;host=somehost;port=3306", "user", "passwd"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //$con = $this->_conn; $stmt = $con->prepare($sql); $stmt->bindParam(':username', $username, PDO::PARAM_STR); $stmt->bindParam(':email', $email, PDO::PARAM_STR); $stmt->bindParam(':passwd', $passwd, PDO::PARAM_STR); } catch ( PDOException $ex ) { die($ex->getMessage()); } $errorList = array (); $totalRows = count($data); for ( $row = 0; $row < $totalRows; $row ++ ) { $username = $data[$row][0]; $email = $data[$row][1]; $passwd = $data[$row][2]; try { $con->beginTransaction(); $stmt->execute(); $con->commit(); } catch ( PDOException $ex ) { // HERE!!! // IF USING $this->_conn AS CONNECTION, SEGFAULT IS PRODUCED ON ROLLBACK! if ( $con->inTransaction() ) $con->rollBack(); // just push the error to an array of failed transactions array_push($errorList, array ( $row, $ex->errorInfo[1], $ex->getMessage() )); } } if ( $errorList ) { // print the errors foreach ( $errorList as $error ) { echo "Row #:" . $error[0] . "<br>"; echo "Code :" . $error[1] . "<br>"; echo "Mesg :" . $error[2] . "<br><br>"; } } } }
What I've also found, if running on my NAS, is that if instead of using $this->_conn as my connection object (which I really should!), I create a NEW PDO object and use that one instead, it works, no segfaults!!
So, the #2 tells me it's the same object! (or am I mistaking?). It should be good. I still tried passing the $con object to my statement constructor as a 'copied' value instead of a reference, and problem remains.. changes nothing! $pdoAttribs = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_AUTOCOMMIT => false, PDO::ATTR_PERSISTENT => true ];
Here's a link to my phpinfo() : http://corbeauperdu.ddns.net/phpinfo.php # Special Configuration file for the DNS-325 # web servers are declared as virtual hosts # include, relative to dirname of main config file include "/etc/lighttpd/lighttpd.conf" # adding extra modules server.modules += ( "mod_redirect" ) server.modules += ( "mod_compress" ) # PRoy: enable compression module server.modules += ( "mod_expire" ) # PRoy: used to set expiry time for cache on clients # add support for new virtual host $HTTP["host"] =~ "(^|\.)myhost.ddns.net$" { server.document-root = "/srv/WWW/html" server.errorlog = "/srv/WWW/logs/error.log" server.error-handler-404 = "/blog/index.php" accesslog.filename = "/srv/WWW/logs/access.log" # files to check for if / is requested index-file.names = ( "index.php", "index.html", "index.htm" ) ########### # PRoy: compress content to DISK as to save CPU-cycles when requesting these file types (otherwise, CPU will compress it all everytime!) compress.allowed-encodings = ("gzip", "deflate") compress.filetype = ("text/plain", "text/html", "text/javascript", "text/css", "text/xml" ) compress.cache-dir = "/srv/WWW/tmp/wwwcache" ########### # PRoy: setup CACHING on clients # make clients think their content is already up-to-date # mod_expire will actually send a Cache-Control / Expires HTTP header on each item it's called upon (css, jpg, or etc) or called URL path # # Cache based on suffix $HTTP["url"] =~ "\.(jpg|gif|png|css|js|eot|svg|ttf|woff|woff2)$" { expire.url = ( "" => "access plus 13 months" ) } # Cache based on path expire.url += ( "/calchom/css/" => "access plus 13 months", "/blog/videos/" => "access plus 13 months", ) # Anything else not caught by mod_expires will be cached on client with these directives setenv.add-response-header += ( # cache for 1 month #"Cache-Control" => "public, max-age=2592000, must-revalidate, proxy-revalidate" # no cache at all! "Cache-Control" => "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0, post-check=0, pre-check=0" ) ########### cgi.assign = (".cgi" => "") static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".cgi" ) flv-streaming.extensions = ( ".flv" ) ########## # PHP Server configuration php-cgi vs php-fpm) # PHP-CGI (2020-02-02 : works good!) # Normally, PHP-FPM should be faster, but not on NAS (?) fastcgi.server = ( ".php" => ("localhost" => ("bin-path" => "/ffp/bin/php-cgi", "socket" => "/tmp/php-cgi.socket", "bin-environment" => ( "PHP_FCGI_CHILDREN" => "0" ), "max-procs" => "1") ) ) ########### server.upload-dirs=( "/srv/WWW/tmp/wwwuploads" ) server.max-request-size = 4194303 server.network-backend="writev" }
Million thanks!! haw can I make a commit script , when I click on button the commit inserted in the table and browsed immediately without refresh the page , like Facebook commits ?
Hit Checkout button the following happens.. Code: [Select] $conn = db_connect(); // we want to insert the order as a transaction // start one by turning off autocommit $conn->autocommit(FALSE); Then order, order_items and customers tables are updated If I then include this code after the order is on the database it commits fine Code: [Select] // end transaction $conn->commit(); $conn->autocommit(TRUE); However I think i have a huge sequence error in that it is only at this point I ask them for the payment card details! If the payment fails I've still commited. I tried moving the $conn->commit(); to the end of the card processing but it just stops at that command I guess because when I went back to solicit the card payment details the plot got lost. I hope this is making sense... Is it possible to keep the transaction / unit of work pending i.e not committed until the result of the next dialog and only commit on a successful card payment else backout? The problem is I can't go to the card payment until I know the entire order process worked. Jamie I am making a project (which I would like to distribute), and I want to load core libraries into main class. Example Main Class: Code: [Select] class Main{ public function loadCore(){ // Load core libraries } } $_main = new Main(); $_main->loadCore(); Once loadCore is run, I would like to load all the files in /root/core/net and /root/core/xml (which I have already done). Next I want to make them easily accessible, but I am not sure of an easy way to access them. I want to make it easy for beginner programmers (and advanced programmers). maybe so they have to do something like this: require_once 'root/Main.php'; // Automatically creates an instance $_main->http->someFunction(); // or $_main->net->http->someFunction(); // or $_main->someFunction(); The example structu Code: [Select] +- root | +- core | | +- net | | | +- Http.php | | | +- Other.php | | | +- Other2.php | | +- xml | | | +- Xml.php | | | +- Other.php | | | +- Other2.php | +- plugins +- Main.php Basically I am just looking for some input on how I could make this SUPER easy to use. The less work the programmer has to do the better. Any thoughts? What is all dependent on PHP?
I mean lets say I removed echo from phps source code.
Then I add function my_echo() which is the exact same code basically, what all would I need to update to allow my_echo() to be implemented correctly
Obviously I would need to modify every one of my php scripts on my webserver to replace echo with my_echo, but is there anything else?
I know i could just append my_echo to phps source, or modify the echo function itself, but this is conceptually and thats not the actual process I'm looking for right now.
Any insight would be greatly appreciated!
How would I write this in php?: Code: [Select] If $url does not begin with 'http://' $url = '' I want to assign nothing to the variable if it doesn't begin with http:// Thanks! Hi, My Client wants me to create one gaming site using Core PHP. We can add flash games via admin. Please assist me to do this. If you any reference, pls send me. Waiting for your favorable responses. thanks, sundar I want to get image background removal with core php like(remove.bg website without using any API)
i want to do it with code any guidance how can i do this with programmatically in php. I am getting these errors . This is my complete HTML page. Everything seems to work fine but when i retweet a message these error show up. Here is my tweet.php and the errors are at line 32 and 41. Previously there was an error at line 24: It was like this: '.((!empty($tweet->retweetMsg) && $tweet->tweetID === $retweet['tweetID'] or $tweet->retweetID > 0) ? ' I changed it to this and the error went away '.((isset($retweet['retweetID']) ? $retweet['retweetID'] === $tweet->retweetID OR $tweet->retweetID > 0 : '') ? ' Maybe this could help! I will really appreciate any suggestion coming my way! Hey guys, I have a folder which has images. In this folder there are images that start with "refl_". I want to make sure those are not displayed. This is what I tried and it does not work. I want to show all images that don't start with "refl_". I am new to this as I am sure some can see. Thanks for the help if possible! <?php $dir = opendir("img/portfolio/"); while (false !== ($file = readdir($dir))) { $pos = strpos($file, "refl_"); if ($pos == false) { echo '<img src="img/portfolio/' . $file . '" longdesc="img/portfolio/' . $file . '" /></a>'; } } ?> Hello, I'm having a bit of a problem here, all help to this issues would be much appreciated I am trying to use text boxes to insert numbers into the database based on what is inputed. If I have a string, like this for example: $variable = 09385493; And I want to insert it into the database like this: mysql_query("INSERT INTO integers(number) VALUES ('$variable')"); When checking the integers table in my database, looking at the number field, the $variable that was inserted is outputted as 9385493 Notice the number zero was taken out of the front of the number. If the number is double 0's (009385493), both of those zero's would disappear, too. Thanks I am using mysqli, OO, to connect to MySQL. I have only today started looking at this and am used to: Code: [Select] <?php $con = mysql_connect();//etc mysql_close($connection); ?> Am I right that with mysqli (OO) that I don't need to set a connection variable wither when connecting or closing?? Code: [Select] <?php mysqli::connect();//etc mysqli::close(); ?> What about with multiple databases, does mysqli keep track for me, as I am used to this: Code: [Select] <?php $con1 = mysql_connect();//db1 $con2 = mysql_connect();//db2 ?> //etc Ok I am trying to use mysqli instead of the usual mysql. Mysql would be outdated. With mysqli, sgl-injection is impossible if you use the "?" in those codes. I would normally use a function but I've made a simple script to find the error. I use $parameters and $sql because these are the data I need to give as parameters to the function, so I used it here too but without the function actually. Code: [Select] ini_set('display_errors',1); // 1 == aan , 0 == uit error_reporting(E_ALL | E_STRICT); # sql debug define('DEBUG_MODE',true); // true == aan, false == uit $userid = 11; $lang = 1; $newLink = "testing123"; $db_host = "localhost"; $db_gebruiker = "root"; $db_wachtwoord = ''; $db_naam = "projecteasywebsite"; $sql= "INSERT tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES(?, ?, ?, ?, ?, ?)"; $parameters = '"iiisis", $userid, 1, 0, $lang, 1, $newLink'; echo $parameters; $mysqli = new mysqli($db_host, $db_gebruiker, $db_wachtwoord, $db_naam); $stmt = $mysqli->prepare($sql); $stmt->bind_param($parameters); $stmt->execute(); echo "<br><br>". mysqli_connect_errno(); echo "<br><br>". mysqli_report(MYSQLI_REPORT_ERROR); $stmt->close(); $mysqli->close(); I got Wrong parameter count for mysqli_stmt::bind_param() So naturally a problem when we execute : Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement ($stmt->execute() Is someone using mysqli too ? hello , I'm starting to use mysqli and i have few questions. is there a guide for mysqli? and how do i use this functions at mysqli ? mysql_num_rows mysql_query mysql_fetch_assoc mysql_fetch_array thanks , Mor.
The below code produces a dropdown and when a selection is made and submitted produces --------------------------------------------------------------------------- <!DOCTYPE><html><head> <title>lookup menu</title> </head> <body><center><b> <form name="form" method="post" action=""> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM lookuptbl"); $query_display = mysqli_query($con,"SELECT * FROM lookuptbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/> </form><center> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target, purpose, user, password, email, visits, date, saved FROM lookuptbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} //display the table echo '<table border="1"><tr><td bgcolor="#ccffff" align="center">lookup menu</td></tr> <tr><td> <table border="1"> <tr> <td> Target </td> <td> Purpose </td> <td> User </td> <td> Password </td> <td> Email </td> <td> Visits </td> <td> Date </td> <td> Saved </td> </tr>'; while($data=mysqli_fetch_row($result)) { $url= "http://localhost/home/crud-link.php?target=". $data[0]; $link= '<a href="'.$url.'">'. $data[0]. '</a>'; echo ("<tr><td> $link </td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td> <td>$data[4]</td><td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>"); } echo '</table> </td></tr></table>'; } ?> </body></html>
When running the following code i get the error: Call to undefined method mysqli::errno() the code: $conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if ($conn->errno() !== 0) { $msg = $conn->error(); throw new connErrorException($msg, 'Connect'); } I am fairly new to classes but as i understand it this should be correct. I am using mysql 5.1 so mysqli is on by default. I have even checked the php ini and everything looks fine there in respect to this. Any advice? Hi, The following code is what I want in that it creates a menu and I can select and display a table row.
I still need to use that selection to update the "lastused". I really appreciate your help. <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <form name="form" method="post" action=""> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); //============== check connection if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} else {echo "Connected to mySQL</br>";} //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select email account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM emailtbl"); $query_display = mysqli_query($con,"SELECT * FROM emailtbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/><!-- update "lastused" using selected "target"--> </form></body></html> <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target,username,password,emailused,lastused, purpose, saved FROM emailtbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} $lastused = "CURDATE()"; // update "lastused" using selected "target" //display the table echo '<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'. 'Email menu'. '</td>'.'</tr>'; echo '<tr>'.'<td>'.'<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'.'target'.'</td>'.'<td bgcolor="#ccffff align="center">'.'username'.'</td>'.'<td bgcolor="#ccffff align="center">'.'password'.'</td>'.'<td bgcolor="#ccffff align="center">'.'emailused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'lastused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'purpose'. '</td>'.'<td bgcolor="#ccffff align="center">'. 'saved' .'</td>'.'</tr>'; while($data=mysqli_fetch_row($result)) {echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td><td>$data[6]</td></tr>");} echo '</table>'.'</td>'.'</tr>'.'</table>'; } ?> </body></html> I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23 Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25 Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33 can someone please explain to me why i am getting these? and my code is $mysqli_db = mysqli_select_db("$db_name"); if($mysqli_db->connect_errno) { printf("Database not found: %s\n", $mysql->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $result = mysqli_query($sql); $row = mysqli_fetch_assoc($result);I just got rid off most the errors the only ones left are Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32 Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33 Code Updated: $mysqli_db = mysqli_select_db($mysqli_connect, $db_name); if(!$mysqli_db) { printf("Database not found: %s\n", $mysqli->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $query = mysqli_query($sql); $result = mysqli_result($query); $row = mysqli_fetch_assoc($result); Edited by Tom8001, 30 November 2014 - 12:43 PM. |