PHP - Updating Mysql To Pdo Or Mysqli
Hello, I've been tasked with updating our code base from mysql to something that will work with php 7. It's older code that was written by 2 or 3 individuals before me and it's not at all object oriented. There are about 540 different files that I will end up having to edit to make it all up to date. I'm not a very experienced programmer myself, and I'm in need of some guidance. There are some files that have functions that call and use mysql queries three or four files deep and going through and editing one function leads me to having to update 4 or 5 other files which breaks stuff somewhere else down the road. I was wondering if anyone has some suggestions on ways to make this process less painful. The other thing is that by using PDO in a not OO style, it seems like I'm losing a lot of its benefits. Should I consider using MYSQLi instead of PDO considering the circumstances? Are there any resources that you could point me to in order to help me learn the skills I need to make it through this upgrade? Thanks for the help! Similar TutorialsI am updating some old code to the IMPROVED version of PHP and running into a problem in this section after connecting successfully to my database: // retrieve the record that was selected $record_id = (isset($_POST['record_id'])) ? $_POST['record_id'] : ''; //check for $record_id emptiness if(!empty($record_id)){ // Retrieve ALL the data from the "example" table $result = mysqli_query($conn, "SELECT * FROM $table WHERE id = $record_id ") or die(mysqli_error()); // store the record of the "example" table into $row $row = mysqli_fetch_array( $result, MYSQLI_BOTH ); } Not sure what I'm missing or what needs to be re-organized. Please advise. Hey. I was writing my class object for a database connection and while I was writing the query part, I came to wonder whether I should use mysql_real_escape_string or mysqli_real_escape_string to make the query mysql friendly, what's the difference? Hello (I think I could have posted this in the wrong PHP area! - so posting it here),
I'm pretty new at building websites using php (and mysql) and was most recently given the task to create a database image gallery, which was to be accessed through a php website.
I made a full site which allowed me to upload said images & it worked perfectly. However after doing my last checks I have been told that mysql is deprecated and that I need to use mysqli.
I've had a look at some tutorials on websites to help direct me but it's simply confusing me more and more each time I look at it.
Is it possible I am over thinking this and there is an easier way to approach it?
Thank you kindly.
This is my php code:
Alright guys, I see people recommending prepared statements (PDO/MySQLi) and saying that they are way to go these days. However upon doing a bit more research, I've found that prepared statements, PDO in particular, is lacking in terms of performance, especially using SELECT statements. Now I'm starting a new project, which is basically a text based game with lots of queries and DB interaction, so I'm really interested in knowing what's the best approach for me. I was leaning towards PDO but I don't want it crawling my server under heavy load. I appreciate any advices or first hand experiences on this. Hi, I only just worked out (a little slow) that mysql is not redundant and crap =\ Apparently I should be using mysqli.
However I need help I tried following a tutorial online but it failed. This is my login script and it doesn't work
<?php require_once '../inc/conn.php'; session_start(); if ($_POST['username']) { $username = $_POST['username']; $password = $_POST['password']; $requestLogin = mysqli_query( $retreat, "SELECT * FROM login WHERE username='$username' AND password='$password'"); while($row = mysqli_fetch_array($requestLogin)){ $userID = $row['userID']; $_SESSION['userID'] = $userID; $username = $row['username']; $_SESSION['username'] = $username; header('location: /administrator/'); } } ?>And this is the conn.php ( something hidden for safety, however it does connect correctly. <?php $hostname = 'localhost'; $username = ''; $password = ''; $database = ''; $retreat = mysqli_connect($hostname, $username, $password, $database) or die('Connecting to MySQL failed'); ?>The actual <form> is also correct as it's just normal html and worked before I tried converting to mysqli. After this login I have a script which is this that goes in the header of all admin pages. <?php require_once '../inc/conn.php'; session_start(); if (isset($_SESSION['userID'])) { $username = $_SESSION['username']; $getUser = mysqli_query( $retreat, "SELECT user_rights FROM login WHERE username='$username'"); while($row = mysqli_fetch_array($getUser)){ $user_rights = $row['user_rights']; } } else { include_once 'login.php'; exit(); } ?>I am no coding professional by any means but I get the job done. However this mysqli is sort of new ground. On the mainpage I am getting this error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\page\controller\function.php on line 393
$result = $db->query($query);And on the admin section: Notice: Undefined index: role in C:\xampp\htdocs\page\admin\header.php on line 7 Notice: Undefined index: role in C:\xampp\htdocs\page\admin\header.php on line 7 Fatal error: Undefined class constant 'site_url' in C:\xampp\htdocs\page\admin\header.php on line 8 if ($_SESSION['role'] !== 'admin' and $_SESSION['role'] !== 'moderator'){header( 'Location:'.config::site_url.'index.php' ); Hi, I am trying to convert the register & login script from mysql to mysqli. I have converted the easy parts and have the connection to the database, but the following functions all need changing and I can't work out the correct solution mainly due to the deprecation of mysql_result() The code that needs updating is <?php function user_count() { return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); } function users_online() { return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `logged_in` = 1"), 0); } function change_profile_image($user_id, $file_temp, $file_extn) { $file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn; move_uploaded_file($file_temp, $file_path); mysql_query("UPDATE `users` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id); } function has_access($user_id, $type) { $user_id = (int)$user_id; $type = (int)$type; return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = $user_id AND `type` = $type"), 0) == 1) ? true : false; } function activate($email, $email_code) { $email = mysql_real_escape_string($email); $email_code = mysql_real_escape_string($email_code); if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == 1) { mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'"); return true; } else { return false; } } function user_exists($username) { $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `username` = '$username'"); return (mysql_result($query, 0) == 1) ? true : false; } function email_exists($email) { $email = sanitize($email); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false; } function user_id_from_username($username) { $username = sanitize($username); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id'); } function user_id_from_email($email) { $email = sanitize($email); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `email` = '$email'"), 0, 'user_id'); } function login($username, $password) { $user_id = user_id_from_username($username); mysql_query("UPDATE `users` SET `logged_in` = 1 WHERE `user_id` = $user_id"); $username = sanitize($username); $password = md5($password); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false; } ?>And here is what the converter gave me: function user_count() { return mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); } function users_online() { return mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(`user_id`) FROM `users` WHERE `logged_in` = 1"), 0); } function change_profile_image($user_id, $file_temp, $file_extn) { $file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn; move_uploaded_file($file_temp, $file_path); mysql_query("UPDATE `users` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id); } function has_access($user_id, $type) { $user_id = (int)$user_id; $type = (int)$type; return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = $user_id AND `type` = $type"), 0) == 1) ? true : false; } function activate($email, $email_code) { $email = mysql_real_escape_string($email); $email_code = mysql_real_escape_string($email_code); if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == 1) { mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'"); return true; } else { return false; } } function user_exists($username) { $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `username` = '$username'"); return (mysql_result($query, 0) == 1) ? true : false; } function email_exists($email) { $email = sanitize($email); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false; } function user_id_from_username($username) { $username = sanitize($username); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id'); } function user_id_from_email($email) { $email = sanitize($email); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `email` = '$email'"), 0, 'user_id'); } function login($username, $password) { $user_id = user_id_from_username($username); mysql_query("UPDATE `users` SET `logged_in` = 1 WHERE `user_id` = $user_id"); $username = sanitize($username); $password = md5($password); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false; } ?>Please could someone point me in the right direction here? Also my site works perfectly well with MySQL, do I have to convert it to MySQLi? Many Thanks Paul If anyone knows how to solve this, it would be much appreciated. I already have a website template and would prefer to continue with mysqli instead of PDO. Many Thanks Paul I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
The MySQLi coding is not working because it would notg insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php error_reporting(1); $submit = $_POST['submit']; //form data $name = mysql_real_escape_string($_POST['name']); $name2 = mysql_real_escape_string($_POST['name2']); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); $password2 = mysql_real_escape_string($_POST['password2']); $email2 = mysql_real_escape_string($_POST['email2']); $address = mysql_real_escape_string($_POST['address']); $address2 = mysql_real_escape_string($_POST['address2']); $address3 = mysql_real_escape_string($_POST['address3']); $address4 = mysql_real_escape_string($_POST['address4']); $error = array(); if ($submit) { //open database $connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error"); //select database mysql_select_db("logindb") or die("Selection Error"); //namecheck $namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'"); $count = mysql_num_rows($namecheck); if($count==0) { } else { if($count==1) { $error[] = "<p><b>User ID taken. Try another?</b></p>"; } } //check for existance if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) { if(strlen($password)<8) { $error[] = "<p><b>Password must be least 8 characters</b></p>"; } if(!preg_match("#[A-Z]+#",$password)) { $error[] = "<p><b>Password must have at least 1 upper case characters</b></p>"; } if(!preg_match("#[0-9]+#",$password)) { $error[] = "<p><b>Password must have at least 1 number</b></p>"; } if(!preg_match("#[\W]+#",$password)) { $error[] = "<p><b>Password must have at least 1 symbol</b></p>"; } //encrypt password $password = sha1($password); $password2 = sha1($password2); if($_POST['password'] != $_POST['password2']) { $error[] = "<p><b>Password does not match</b></p>"; } //rescue email match check if($_POST['email2'] == $_POST['email']) { $error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>"; } //generate random code $random = rand(11111111,99999999); //check for error messages if(isset($error)&&!empty($error)) { implode($error); } else { //Registering to database $queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')"); $lastid = mysql_insert_id(); echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>"; die (); } } } ?>MYSQLi (NOT WORKING AFTER CONVERTING) <?php error_reporting(1); $submit = $_POST['submit']; //form data $name = mysqli_real_escape_string($connect, $_POST['name']); $name2 = mysqli_real_escape_string($connect, $_POST['name2']); $email = mysqli_real_escape_string($connect, $_POST['email']); $password = mysqli_real_escape_string($connect, $_POST['password']); $password2 = mysqli_real_escape_string($connect, $_POST['password2']); $email2 = mysqli_real_escape_string($connect, $_POST['email2']); $address = mysqli_real_escape_string($connect, $_POST['address']); $address2 = mysqli_real_escape_string($connect, $_POST['address2']); $address3 = mysqli_real_escape_string($connect, $_POST['address3']); $address4 = mysqli_real_escape_string($connect, $_POST['address4']); $error = array(); if ($submit) { //open database $connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error"); //namecheck $namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'"); $count = mysqli_num_rows($namecheck); if($count==0) { } else { if($count==1) { $error[] = "<p><b>User ID taken. Try another?</b></p>"; } } //check for existance if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) { if(strlen($password)<8) { $error[] = "<p><b>Password must be least 8 characters</b></p>"; } if(!preg_match("#[A-Z]+#",$password)) { $error[] = "<p><b>Password must have at least 1 upper case characters</b></p>"; } if(!preg_match("#[0-9]+#",$password)) { $error[] = "<p><b>Password must have at least 1 number</b></p>"; } if(!preg_match("#[\W]+#",$password)) { $error[] = "<p><b>Password must have at least 1 symbol</b></p>"; } //encrypt password $password = sha1($password); $password2 = sha1($password2); if($_POST['password'] != $_POST['password2']) { $error[] = "<p><b>Password does not match</b></p>"; } //rescue email match check if($_POST['email2'] == $_POST['email']) { $error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>"; } //generate random code $random = rand(11111111,99999999); //check for error messages if(isset($error)&&!empty($error)) { implode($error); } else { //Registering to database $queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')"); $lastid = mysqli_insert_id(); echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>"; die (); } } } ?> Hi there,
I'm new to all this so I've been following instructions from various sites and books. So far I have installed Apache, PHP and mysql, however when I browse to localhost/test.php (created to view phpinfo() through the browser) i can't see mysql or mysqli only the mysqlnd.
Here is an overview of software I've installed, OS and things I've added so far;
OS ver Windows7 Professional 32-bit VM how i can make a insert using this fuctions I m learning php, as using this functions (mysqli abstract) but after update wont work any more.
/** insert data array */ public function insert(array $arr) { if ($arr) { $q = $this->make_insert_query($arr); $return = $this->modifying_query($q); $this->autoreset(); return $return; } else { $this->autoreset(); return false; } }complement /** insert query constructor */ protected function make_insert_query($data) { $this->get_table_info(); $this->set_field_types(); if (!is_array(reset($data))) { $data = array($data); } $keys = array(); $values = array(); $keys_set = false; foreach ($data as $data_key => $data_item) { $values[$data_key] = array(); $fdata = $this->parse_field_names($data); foreach ($fdata as $key => $val) { if (!$keys_set) { if (isset($this->field_type[$key])) { $keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`'; } else { $keys[] = '`' . $val['field'] . '`'; } } $values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key), $this->is_bit($key)); } $keys_set = true; $values[$data_key] = '(' . implode(',', $values[$data_key]) . ')'; } $ignore = $this->ignore ? ' IGNORE' : ''; $delayed = $this->delayed ? ' DELAYED' : ''; $query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',', $values); return $query; }before update this class i used to insert data like this $db = Sdba::table('users'); $data = array('name'=>'adam'); $db->insert($data);this method of insert dont works on new class. if i try like this i got empty columns and empty values. thanks for any help complete class download http://goo.gl/GK3s4E I have a prepared statement class for MYSQL, since in PHP 5 this is now changing to mysqli; I'm looking for some help in changing the code from my existing class to the new mysqli.
I have done some research online about changing from mysql to mysqli but the changes I made seems to only cause issues with connecting to the database.
After many hours of changing the existing file using the research online, I've decided to start again and ask others if they would be ever so kind to help this noob out and point out which parts of the script needs to be changed.
Thank you for reading.
<?php class Database { private $host; private $user; private $pass; private $name; private $link; private $error; private $errno; private $query; function __construct($host, $user, $pass, $name = "", $conn = 1) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; if (!empty($name)) $this -> name = $name; if ($conn == 1) $this -> connect(); } function __destruct() { @mysql_close($this->link); } public function connect() { if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass, TRUE)) { if (!empty($this -> name)) { if (!mysql_select_db($this -> name, $this->link)) $this -> exception("Could not connect to the database!"); } } else { $this -> exception("Could not create database connection!"); } } public function close() { @mysql_close($this->link); } public function query($sql) { if ($this->query = @mysql_query($sql, $this->link)) { return $this->query; } else { $this->exception("Could not query database!"); return false; } } public function num_rows($qid) { if (empty($qid)) { $this->exception("Could not get number of rows because no query id was supplied!"); return false; } else { return mysql_num_rows($qid); } } public function fetch_array($qid) { if (empty($qid)) { $this->exception("Could not fetch array because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid); } return $data; } public function fetch_array_assoc($qid) { if (empty($qid)) { $this->exception("Could not fetch array assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid, MYSQL_ASSOC); } return $data; } public function fetch_object($qid) { if (empty($qid)) { $this->exception("Could not fetch object assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_object($qid); } return $data; } public function fetch_all_array($sql, $assoc = true) { $data = array(); if ($qid = $this->query($sql)) { if ($assoc) { while ($row = $this->fetch_array_assoc($qid)) { $data[] = $row; } } else { while ($row = $this->fetch_array($qid)) { $data[] = $row; } } } else { return false; } return $data; } public function last_id() { if ($id = mysql_insert_id()) { return $id; } else { return false; } } private function exception($message) { if ($this->link) { $this->error = mysql_error($this->link); $this->errno = mysql_errno($this->link); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } if (PHP_SAPI !== 'cli') { ?> <div class="alert-bad"> <div> Database Error </div> <div> Message: <?php echo $message; ?> </div> <?php if (strlen($this->error) > 0): ?> <div> <?php echo $this->error; ?> </div> <?php endif; ?> <div> Script: <?php echo @$_SERVER['REQUEST_URI']; ?> </div> <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?> <div> <?php echo @$_SERVER['HTTP_REFERER']; ?> </div> <?php endif; ?> </div> <?php } else { echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n"; }; } } ?> Hi, Apologies to keep going on about this but I have hit a brick wall over updating my database with XML. I have spent around 100 hours on this and so far I can only copy the file, I am unable so far to update my database with the information from the XML file. I would be very grateful for any help you can offer to fix this. Code: [Select] ----Code so far----> $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "http://www.domain.co.uk/datafeed.xml"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $prod = new SimpleXMLElement($domString); $id = $prod->prod['id']; $description = $prod->name; $image = $prod->awImage; $fulldescription = $prod->desc; //insert query if(strlen($prod) > 0) { $query = mysql_query("REPLACE INTO productfeed (id, description, fulldescription, image) VALUES ('$id','$description','$image','$fulldescription') "); echo $id . "has been inserted </br>"; } else{echo ("This does not work </br>");} } This is an outline of the XML feed I am using, it only includes one item which I am using as a test: Code: [Select] - <merchant id="1829" name="Pinesolutions.co.uk"> - <prod id="39920873" pre_order="no" web_offer="no" in_stock="yes" hotPick="no" adult="no"> - <text lang="EN"> <name>Oakleigh Wall Mirror 60x90</name> <desc>Mirrors are useful anywhere in the house. Not only are they functional allowing you to see your reflection in order to look your best, they also add elegance to any room theyre placed in. We offer a variety of mirrors to fit your decorating tastes as well as wall space. The Oakleigh Wall Mirror radiates an elegant simplistic style, while offering a generous size glass. The Oakleigh Wall Mirror s frame is crafted from solid hardwood and is lacquered with a protective finish to guard against dust and unexpected stains. The Oakleigh Wall Mirror is versatile and can be hung portrait style at the top of a staircase or landscape. The Oakleigh Wall Mirrors light colour means it also complements all of the furniture in our Camden Painted Range because the range has ash tops. The Oakleigh Wall Mirror has fewer knots than traditional oak wood, but is built just as sturdy so you can be certain it will last you through the generations to come.</desc> </text> - <uri lang="EN"> <awTrack>http://www.awin1.com/pclick.php?p=39920873&a=98057&m=1829</awTrack> <awImage>http://images.productserve.com/preview/1829/39920873.jpg</awImage> <mLink>http://www.pinesolutions.co.uk/bedroom-furniture/mirrors/wall-mirrors/oakleigh-wall-mirror-60x90/</mLink> <mImage>http://media.pinesolutions.co.uk/images/products/903.333.3.4.jpg</mImage> </uri> - <price curr="GBP"> <buynow>40.00</buynow> </price> - <cat> <awCatId>424</awCatId> </cat> <brand /> </prod> </merchant> Hi, Does anyone have any experience of using PHP to transfer data from an XML file to a MySQL database? For the last 5 weeks I have been trying to get the following code to work but I am still unable to do it. The code does copy the file from my root folder into another (I eventually plan to use external download onto my server). However, it comes up with the following error: "Cannot instantiate non-existent class: xmlreader in" which refers to this: $xmlReader = new XMLReader(); Does anyone have any experience of transferring data from an XML file to a database? I am using PHP 5 so I dont know why this doesn't work. <?php ini_set('display_errors', 1); error_reporting(-1); $host="hostname"; // $username="username"; // $password="password"; // $db_name="db"; // $tbl_name="productfeed"; // // Connect to server and select database. mysql_connect("$host", "$username", "$password")or ("no connection"); mysql_select_db("$db_name")or die("Database Connection Error"); $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "[url=http://www.ukhomefurniture.co.uk/datafeed.xml]http://www.ukhomefurniture.co.uk/datafeed.xml[/url]"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $product = new SimpleXMLElement($domString); $product_code = $product->prod['id']; $image = $product->awImage; //insert query if(strlen($product) > 0) { $query = mysql_query("REPLACE INTO productfeed (image) VALUES ('$awImage')"); echo $awImage . "has been inserted </br>"; die('yes it works'); error_reporting(E_ALL); if (ini_get('display_errors')) { ini_set('display_errors', 1); } } break; } } ?> MOD EDIT: DB credentials removed. How can I store data which is in a email to a MySQL db? Currently I'm receiving all enquirers in to my INBOX. I need a way to upload data which is in the mail direct from my email page to a MySQL db. is this possible? or what's the best way to approach this? Hi, when someone logs in to my page, i have a form displayed with names, address, etc...what i need to do is when i hit the update button for that information to go into the MYSQL table I have created and over write that information if a user updates...so how do i do that? Hey guys, I have a private message script but for some reason when its updating, it turns the value into a blank one from 1 to 3. I have no idea why, but it works with the old statement of deleting, but I changed it to instead update it to 3 because I want to keep the pm in archives. here is the delete PM part. <?php session_start(); header("Location:inbox.php"); $user = $_SESSION['username']; include 'db.php'; //We do not have a user check on this page, because it seems silly to, you just send data to this page then it directs you right back to inbox //We need to get the total number of private messages the user has $sql = mysql_query ("SELECT pm_count FROM users WHERE username='$user'"); $row = mysql_fetch_array ($sql); $pm_count = $row['pm_count']; //A foreach loop for each pm in the array, get the values and set it as $pm_id because they were the ones selected for deletion foreach($_POST['pms'] as $num => $pm_id) { //Delete the PM from the database mysql_query("UPDATE messages SET recieved='3' WHERE id='$pm_id' AND reciever='$user'"); // mysql_query("DELETE FROM messages WHERE id='$pm_id' AND reciever='$user'"); //Subtract a private message from the counter! YAY! //$pm_count = $pm_count - '1'; //Now update the users message count with the new value //mysql_query("UPDATE users SET pm_count='$pm_count' WHERE username='$user'"); } ?> The commented out part at the end, is the old deleting parts but instead changed it to update value. Here is my form that shows checkboxes. I showed the whole code, where it has comments. <?php //This stuff and the while loop will query the database, see if you have messages or not, and display them if you do $query = "SELECT id, sender, subject, message FROM messages WHERE reciever='$user' AND recieved='1'"; $sqlinbox = mysql_query($query); //We have a mysql error, we should probably let somone know about the error, so we should print the error if(!$sqlinbox) { ?> <p><?php print '$query: '.$query.mysql_error();?></p> <?php } //There are no rows found for the user that is logged in, so that either means they have no messages or something broke, lets assume them they have no messages elseif (!mysql_num_rows($sqlinbox) ) { ?> <center><p><b>You havent read any messages</b></p></center> <?php } //There are no errors, and they do have messages, lets query the database and get the information after we make a table to put the information into else { //Ok, Lets center this whole table Im going to make just because I like it like that //Then we create a table 80% the total width, with 3 columns, The subject is 75% of the whole table, the sender is 120 pixels (should be plenty) and the select checkboxes only get 25 pixels ?> <center> <form name="send" method="post" action="delete.php"> <table width="80%"> <tr> <td width="75%" valign="top"><p><b><u>Subject</u></b></p></td> <td width="120px" valign="top"><p><b><u>Sender</u></b></p></td> <td width="25px" valign="top"><p><b><u>Select</u></b></p></td> </tr> <?php //Since everything is good so far and we earlier did a query to get all the message information we need to display the information. //This while loop goes through the array outputting all of the message information while($inbox = mysql_fetch_array($sqlinbox)) { //These are the variables we get from the array as it is going through the messages, we have the id of the private message, we have the person who sent the message, we have the subject of the message, and yeah thats it $pm_id = $inbox['id']; $sender = $inbox['sender']; $subject = $inbox['subject']; //So lets show the subject and make that a link to the view message page, we will send the message id through the URL to the view message page so the message can be displayed //And also let the person see who sent it to them, if you want you can make that some sort of a link to view more stuff about the user, but Im not doing that here, I did it for my game though, similar to the viewmsg.php page but a different page, and with the senders id //And finally the checkboxes that are all stuck into an array and if they are selected we stick the private message id into the array //I will only let my users have a maximum of 50 messages, remeber that ok? Because that's the value I will later in another page //Here is finally the html output for the message data, the while loop keeps going untill it runs out of messages ?> <tr> <td width="75%" valign="top"><p><a href="viewmsg.php?msg_id=<?php echo $pm_id; ?>"><?php echo $subject; ?></a></p></td> <td width="120px" valign="top"><p><?php echo $sender; ?></p></td> <td width="25px" valign="top"><input name="pms[]" type="checkbox" value="<?php echo $pm_id; ?>"></td> </tr> <?php //This ends the while loop } //Here is a submit button for the form that sends the delete page the message ids in an array ?> <tr> <td colspan="3"><input type="submit" name="Submit" value="Delete Selected"></td> <td></td> <td></td> </tr> </table> </center> <?php //So this ends the else to see if it is all ok and having messages or not } ?> So yeah, does anyone know why it updates it to a blank value, from the value 1 in recieved? is it possible to update data in mysql when a user clicks logout? Hi All, Whenever I try to update any piece of PHP code to update a MySQL database, nothing happens. I have tried copying in some of the working codes of a website and tried the same, but no success. I recently installed XAMPP. I am connecting using the correct user id and pass to the database. The scripts are not giving me any error, but just not connecting, that's all. While making such a usage as noted below <FORM name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > I get the following error Firefox can't find the file at /C:/xampp/htdocs/="<?php.. so on Why does this happen? I am pretty new to this, so please do help. Thanks, Satheesh P R Hello folks, I can not seem to find out why this code is not being executed properly. Basically, I'd like to edit Records, so I am using forms to retrieve data, make modifications then save them. Code: [Select] <?php //connection to db $results = mysql_query("SELECT * FROM crud WHERE id=".$_GET[id]."") or die (mysql_error()); $row = mysql_fetch_assoc($results); echo "<form action=\"\" method=\"POST\">"; echo "Year: <input type=\"text\" value=".$row['car_year']." name=\"car_year\" /> <br />"; echo "Make: <input type=\"text\" value=".$row['car_make']." name=\"car_make\" /> <br />"; echo "Model: <input type=\"text\" value=".$row['car_model']." name=\"car_model\" /><br /><br />"; echo "Description:<br /><textarea rows=\"15\" cols=\"60\" name=\"description\" />". $row['description']. "</textarea>"; echo "<br /><input type=\"submit\" value=\"save\">"; echo "</form>"; if ($_POST['save']) { $car_year = $_POST['car_year']; $car_make = $_POST['car_make']; $car_model = $_POST['car_model']; $description = $_POST['description']; // Update data $update = mysql_query("UPDATE crud SET car_year='$car_year', car_make='$car_make' car_model='$car_model', description='$description' WHERE id=".$_GET['id']."") or die (mysql_error()); echo 'Update successfull'; } ?> Please HELP!!!! For the last few days I have been trying to work out why my code does not update the MySQL database table. Having tried several variation I have the below but cannot see anything wrong. The rest of the program produces the correct results (displaying what is currently on the table) showing it is connecting to the correct table but altering the table is not working. Any help greatly appreciated. The few lines in question a Code: [Select] // Update the profile data in the database if (!$error) { if (!empty($name)&& !empty($phone) && !empty($address1) && !empty($address2)) { // Only set the picture column if there is a new picture if (!empty($new_picture)) { //if (!empty($postcode)){ $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', picture = '$new_picture', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; } mysqli_query($dbc, $query) or die("<br>Query $query<br>Failed with error: " . mysqli_error($dbc) . '<br>On line: ' . __LINE__); The whole program is below Code: [Select] <?php error_reporting(E_ALL); session_start(); ?> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (!isset($_GET['user_id'])) { $query = "SELECT * FROM antique WHERE user_id = '" . $_SESSION['user_id'] . "'"; } else { $query = "SELECT * FROM antique WHERE user_id = '" . $_GET['user_id'] . "'"; } $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 1) { // The user row was found so display the user data $row = mysqli_fetch_array($data); echo '<table>'; if (!empty($row['name'])) { echo '<tr><td class="label">Name:</td><td>' . $row['name'] . '</td></tr>'; } if (!empty($row['phone'])) { echo '<tr><td class="label">Phone:</td><td>' . $row['phone'] . ' </td></tr>'; } if (!empty($row['address1'])) { echo '<tr><td class="label">Address1:</td><td>' . $row['address1'] . ' </td></tr>'; } if (!empty($row['address2'])) { echo '<tr><td class="label">Address2:</td><td>' . $row['address2'] . ' </td></tr>'; } if (!empty($row['postcode'])) { echo '<tr><td class="label">Postcode:</td><td>' . $row['postcode'] . ' </td></tr>'; } if (!empty($row['webadd'])) { echo '<tr><td class="label">Web address:</td><td>' . $row['webadd'] . ' </td></tr>'; } if (!empty($row['email'])) { echo '<tr><td class="label">Email:</td><td>' . $row['email'] . ' </td></tr>'; } if (!empty($row['username'])) { echo '<tr><td class="label">Username:</td><td>' . $row['username'] . ' </td></tr>'; } if (!empty($row['user_id'])) { echo '<tr><td class="label">User ID:</td><td>' . $row['user_id'] . ' </td></tr>'; } echo '</table>'; //echo '<class = "label">USER ID: ' . $_SESSION['user_id'] . ''; if (!isset($_GET['postcode']) || ($_SESSION['postcode'] == $_GET['postcode'])) { echo '<p>Would you like to <a href="index5.php">Go to Homepage</a>?</p>'; } } // End of check for a single row of user results else { echo '<p class="error">There was a bit of a problem accessing your profile.</p>'; } ?> <hr> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Make sure the user is logged in before going any further. if (!isset($_SESSION['user_id'])) { echo '<p class="login">Please <a href="login1.php">log in</a> to access this page.</p>'; exit(); } // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (isset($_POST['submit'])) { // Grab the profile data from the POST $name = mysqli_real_escape_string($dbc, trim($_POST['name'])); $phone = mysqli_real_escape_string($dbc, trim($_POST['phone'])); $address1 = mysqli_real_escape_string($dbc, trim($_POST['address1'])); $address2 = mysqli_real_escape_string($dbc, trim($_POST['address2'])); $postcode = mysqli_real_escape_string($dbc, trim($_POST['postcode'])); $webadd = mysqli_real_escape_string($dbc, trim($_POST['webadd'])); $email = mysqli_real_escape_string($dbc, trim($_POST['email'])); $old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture'])); $new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name'])); $new_picture_type = $_FILES['new_picture']['type']; $new_picture_size = $_FILES['new_picture']['size']; $username = mysqli_real_escape_string($dbc, trim($_POST['username'])); $user_id = mysqli_real_escape_string($dbc, trim($_POST['user_id'])); if (!empty($_FILES['new_picture']['tmp_name'])) {list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); } //list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); $error = false; // Validate and move the uploaded picture file, if necessary if (!empty($new_picture)) { if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') || ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) && ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) { if ($_FILES['new_picture']['error'] == 0) { // Move the file to the target upload folder $target = MM_UPLOADPATH . basename($new_picture); if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) { // The new picture file move was successful, now make sure any old picture is deleted if (!empty($old_picture) && ($old_picture != $new_picture)) { } } else { // The new picture file move failed, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Sorry, there was a problem uploading your picture.</p>'; } } } else { // The new picture file is not valid, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) . ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>'; } } $error = false; // Update the profile data in the database if (!$error) { if (!empty($name)&& !empty($phone) && !empty($address1) && !empty($address2)) { // Only set the picture column if there is a new picture if (!empty($new_picture)) { //if (!empty($postcode)){ $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', picture = '$new_picture', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; } mysqli_query($dbc, $query) or die("<br>Query $query<br>Failed with error: " . mysqli_error($dbc) . '<br>On line: ' . __LINE__); // Confirm success with the user echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile4.php">view your profile</a>?</p>'; mysqli_close($dbc); exit(); } else { echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>'; } } // End of check for form submission else { // Grab the profile data from the database $query="SELECT * FROM antique WHERE user_id= '" . $row['user_id'] . "'"; $data = mysqli_query($dbc, $query); $row = mysqli_fetch_array($data); if ($row != NULL) { $name = $row['name']; $phone = $row['phone']; $address1 = $row['address1']; $address2 = $row['address2']; $postcode = $row['postcode']; $email = $row['email']; $webadd = $row['webadd']; $old_picture = $row['picture']; $username = $_SESSION['username']; $user_id = $row['user_id']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } mysqli_close($dbc); ?> <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" /> <fieldset> <legend>Personal Information</legend> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br /> <label for="phone">Phone:</label> <input type="text" id="phone" name="phone" value="<?php if (!empty($phone)) echo $phone; ?>" /><br /> <label for="address1">Address1:</label> <input type="text" id="address1" name="address1" value="<?php if (!empty($address1)) echo $address1; ?>" /><br /> <label for="address2">Address2:</label> <input type="text" id="address2" name="address2" value="<?php if (!empty($address2)) echo $address2; ?>" /><br /> <label for="postcode">Postcode:</label> <input type="text" id="postcode" name="postcode" value="<?php if (!empty($postcode)) echo $postcode; ?>" /><br /> <label for="email">Email:</label> <input type="text" id="email" name="email" value="<?php if (!empty($email)) { echo $email; } else { echo 'No email entered';} ?>" /><br /> <label for="webadd">Web address:</label> <input type="text" id="webadd" name="webadd" value="<?php if (!empty($webadd)) { echo $webadd; } else { echo 'No web address entered';} ?>" /><br /> <input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" /> <label for="new_picture">Pictu </label> <input type="file" id="new_picture" name="new_picture" /> <?php if (!empty($old_picture)) { echo '<img class="profile" src="' . MM_UPLOADPATH . $old_picture . '" alt="Profile Picture" style: height=100px;" />'; } ?> <br /> <label for="username">Username:</label> <input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br /> <label for="user_id">User ID:</label> <input type="text" id="user_id" name="user_id" value="<?php echo '' . $row['user_id'] . '' ; ?>" /><br /> </fieldset> <input type="submit" value="Save Profile" name="submit" /> </form> <?php echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. <a href="logout3.php">Log out</a>.</p>'); echo '<class = "label">USER ID: ' . $row['user_id'] . ''; ?> <p><a href="index.php">Return to homepage</a></p> <?php require_once('footer.php'); ?> </body> </html> |