PHP - Php/mysql Post Problem
Similar TutorialsHey y'all, I'm trying to write a PHP script for a login function. There are three elements, two text fields (username and password) and a button which calls the script. Segment from index.php file: <form action = "login.php" method = "POST"> Admin Login: <br> Username: <input type = "text" name = "usernameField"/><br> <!-- Password field--> Password: <input type = "password" name = "passwordField"/><br> <!-- Username field --> <input type = "button" value = "Login" name = "submitButton"/> <!-- Login button --> </form> Segment from login.php file: <?php $connect = mysql_connect("localhost", "root", "root"); if(!$connect){//If user can't connect to database die('Could not connect: ' . mysql_error()); //Throw an error } mysql_select_db("colin_db", $connect); //Get given username and password from username field and password field $givenUsername = $_POST["usernameField"]; $givenPassword = $_POST["passwordField"]; $myQuery = "SELECT * FROM ADMINS WHERE USERNAME = '$givenUsername' AND PASSWORD = '$givenPassword'"; $queryResult = mysql_query($myQuery); $numRows = mysql_num_rows($queryResult); if($numRows == 1){ //If the details are correct... //Reload the page and login echo "<script type = 'text/javascript'> window.location.reload() </script>"; } elseif($numRows == 0){ //Else if the details are not found //Display error accordingly echo "Details not correct!"; } mysql_close($connect); ?> The problem is, when I click the login button, it doesn't do anything. What am I missing? (The information in the database is correct) Thanks, Jake original sql Code: [Select] -- -------------------------------------------------------- -- -- Table structure for table `countries` -- CREATE TABLE `countries` ( `id` int(6) NOT NULL auto_increment, `value` varchar(250) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=243 ; -- -- Dumping data for table `countries` -- INSERT INTO `countries` VALUES (1, 'Vancouver'); New Sql Code: [Select] -- -------------------------------------------------------- -- -- Table structure for table `countries` -- CREATE TABLE `countries` ( `id` int(6) NOT NULL auto_increment, `value` varchar(250) NOT NULL default '', `code` varchar(12) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=243 ; -- -- Dumping data for table `countries` -- INSERT INTO `countries` VALUES (1, 'Vancouver', 'BC-50'); PHP code for the job Code: [Select] <?php // PHP5 Implementation - uses MySQLi. // mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase'); $db = new mysqli('localhost', 'root' ,'password', 'weather'); if(!$db) { // Show error if we cannot connect. echo 'ERROR: Could not connect to the database.'; } else { // Is there a posted query string? if(isset($_POST['queryString'])) { $queryString = $db->real_escape_string($_POST['queryString']); // Is the string length greater than 0? if(strlen($queryString) >0) { // Run the query: We use LIKE '$queryString%' // The percentage sign is a wild-card, in my example of countries it works like this... // $queryString = 'Uni'; // Returned data = 'United States, United Kindom'; // YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE. // eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE '$queryString%' LIMIT 10 $query = $db->query("SELECT your_column FROM your_db_table WHERE your_column LIKE '$queryString%' LIMIT 10"); if($query) { // While there are results loop through them - fetching an Object (i like PHP5 btw!). while ($result = $query ->fetch_object()) { // Format the results, im using <li> for the list, you can change it. // The onClick function fills the textbox with the result. // YOU MUST CHANGE: $result->value to $result->your_colum echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>'; } } else { echo 'ERROR: There was a problem with the query.'; } } else { // Dont do anything. } // There is a queryString. } else { echo 'There should be no direct access to this script!'; } } ?> What the original code does 1) you start typing your city (eg. Van) 2) when you type the first letter (eg. V), it looks into mysql and auto fills a dropdown menu with all possible cities What i need it to do 1) you start typing your city (eg. Van) 2) when you type the first letter (eg. V), it looks into mysql and auto fills a dropdown menu with all possible cities 3) when you find your city you click it or press enter, and it POST's the city code as well now how do i munipulate the script to do that... another thing, when i put the extra sql entry in "code", the auto fill stopped working, why? Thanks I need to check post values with existing database values and my check isn't working for the values below. Code: [Select] //This one works if ((isset($_POST['companystageas'])) && ($_POST['companystageas'] != $info['stage'])) { $details = ''; update_company_actions($info['companyid'], 10, $details); } //These all fail if ((!isset($_POST['companystateas'])) && (($_POST['companycountryas'] != $info['country']) || ($_POST['city'] != $info['city']))) { $details = $_POST['companycityas'].', '.$_POST['companycountryas']; update_company_actions($info['companyid'], 11, $details); } else if ((isset($_POST['companystateas'], $_POST['companycityas'])) && (($_POST['companystateas'] != $info['state']) || ($_POST['companycityas'] != $info['city']))) { $details = $_POST['companycityas'].', '.$_POST['companystateas']; update_company_actions($info['companyid'], 11, $details); } if ((isset($_POST['capitalrequestedas'])) && ($_POST['capitalrequestedas'] != $info['capitalrequested'])) { $details = ''; update_company_actions($info['companyid'], 12, $details); }
Hello, I am a newbie regarding PHP and have done mostly only front-end web design for a couple of years and recently started querying DB's and displaying the data, but now this is a new project.
I've tested code snippets as the ones below, but fail to incorporate them in the bigger picture of what I'm trying to achieve. <?php // https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 class DumpHTTPRequestToFile { public function execute($targetFile) { $data = sprintf( "%s %s %s\n\nHTTP headers:\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach ($this->getHeaderList() as $name => $value) { $data .= $name . ': ' . $value . "\n"; } $data .= "\nRequest body:\n"; file_put_contents( $targetFile, $data . file_get_contents('php://input') . "\n" ); echo("Done!\n\n"); } private function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { // convert HTTP_HEADER_NAME to Header-Name $name = strtr(substr($name,5),'_',' '); $name = ucwords(strtolower($name)); $name = strtr($name,' ','-'); // add to list $headerList[$name] = $value; } } return $headerList; } } (new DumpHTTPRequestToFile)->execute('./dumprequest.csv'); This snippet also seems to return the headers and their values but I don't know how to efficiently write and append it to a TXT or CSV, or preferably, directly into a MySQL database. <?php foreach (getallheaders() as $name => $value) { echo "$name: $value"; echo "<br>"; } ?>
Any help towards storing the header values of HTTP POST requests into a database would be greatly appreciated! Once upon a time needed help on March 12, 2008 this community helped me, I am still a learner tried to help back but all the problems posted here beyond my skills to solve them so I kept quiet. and Now I need help once again hope I will get it done. Its PHPPOS developed in Codeigniter This code below is from application\controllers\inventory_summary.php file Code: [Select] <?php require_once("report.php"); class Inventory_summary extends Report { function __construct() { parent::__construct(); } public function getDataColumns() { return array($this->lang->line('reports_item_name'), $this->lang->line('reports_item_number'), $this->lang->line('reports_description'), $this->lang->line('reports_count'), $this->lang->line('reports_reorder_level')); } public function getData(array $inputs) { $this->db->select('name, item_number, quantity, reorder_level, description'); $this->db->from('items'); $this->db->where('deleted', 0); $this->db->order_by('name'); return $this->db->get()->result_array(); } public function getSummaryData(array $inputs) { return array(); } } ?> And this partial code below is from application\controllers\report.php file Code: [Select] function inventory_summary($export_excel=0) { $this->load->model('reports/Inventory_summary'); $model = $this->Inventory_summary; $tabular_data = array(); $report_data = $model->getData(array()); foreach($report_data as $row) { $tabular_data[] = array($row['name'], $row['item_number'], $row['description'], $row['quantity'], $row['reorder_level']); } $data = array( "title" => $this->lang->line('reports_inventory_summary_report'), "subtitle" => '', "headers" => $model->getDataColumns(), "data" => $tabular_data, "summary_data" => $model->getSummaryData(array()), "export_excel" => $export_excel ); $this->load->view("reports/tabular",$data); } } ?> Together they get the job done as follow: Item Name Item Number Description Count Reorder Level (Count is quantity in stock) Item 1 0002 xyz 5 3 Item 2 0s00 xyz 5 3 Item 3 0005 xyz 5 3 Item 4 0006 xyz 5 3 The output I want need to be like this: Item Name Item Number Description cost price Count Reorder Level Item 1 0002 xyz 250 5 3 Item 2 0s00 xyz 120 5 3 Item 3 0005 xyz 300 5 3 Item 4 0006 xyz 500 5 3 Total Stock Value 5850 Total Count 20 <-- this doesn't require any formation just needs to be at bottom of all the queries like shown here. This is what I want mainly >>>>>>>>>> Total Stock Value (cost price * count foreach and then sum of all results ) and sum of all count cost price table and column is different than one used above in the code which is: databse table is ' receivings_items ' Column is 'item_cost_price' example php code to fetch is : Code: [Select] $sql = "SELECT `item_cost_price` FROM `receivings_items`"; config.php contains all the connection variables to MySQL Please Help me I have a post.php that is suposted to run a mysql query, and it used to, but it won't anymore and I don't have the old file. Can someone just look see if there is something i'm missing? <?php //header("Location: ./?p=UCP"); setcookie("Errors", 0, time()-3600); // Connects to your Database mysql_connect("SERVER", "USER", "PASS") or die(mysql_error()); mysql_select_db("DB") or die(mysql_error()); if (isset($_POST['remove'])) { $id=$_POST['ID']; if($_POST['initals'] == "NLW") { if (is_numeric ($id)) { mysql_query("DELETE FROM `users` WHERE `users`.`ID` = $id LIMIT 1"); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "User Removed."; $error .="</span>"; setcookie(Errors, $error, time()+20); } else { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Please enter a valid ID"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } } else { $error="<span style="; $error .="color:red"; $error .=">"; $error .="Initials are not correct"; $error .="<span/>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } } elseif (isset($_POST['submit'])) { //This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "You did not complete all of the required fields"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Sorry, the username is already in use."; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= 'Your passwords did not match.'; $error .="</span>"; setcookie(Errors, $error, time()+20); echo $error; } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); $_POST['pass2'] = $_POST['pass2']; } // now we insert it into the database $insert = "INSERT INTO users (username, password, Human-Readable) VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['pass2']."')"; mysql_query("INSERT INTO users (username, password, Human-Readable) VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['pass2']."')"); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "<h1>User Registered</h1> <p><h2>Thank you, the user has been registered - he/she may now login</a>.</h2></p>"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location: ./?p=UCP'); } else { header('Location: ./?p=UCP'); echo $error; } ?> The remove function works but its the submit. Thanks in advanced I have a photo album style gallery to build and i'm finding it dificult to list all the table names (these are names of photo albums) and then enter the data into a seperate query for each album name (these will change often so i cant keep updating the file as normal. this will then post all the data to the xml file and show the set of photos in the individual albums in a flash file. can anyone help me where im going wrong at all? <?php $dbname = 'cablard'; if (!mysql_connect('localhost', 'cablard', '')) { echo 'Could not connect to mysql'; exit; } $sql = "SHOW TABLES FROM $dbname"; $result = mysql_query($sql); if (!$result) { echo "DB Error, could not list tables\n"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}\n"; } mysql_free_result($result); $query = "SELECT * FROM photo ORDER BY id DESC"; $result2 = mysql_query ($query) or die ("Error in query: $query. ".mysql_error()); while ($row = mysql_fetch_array($result2)) { echo " <image> <date>".$row['date']."</date> <title>".$row['title']."</title> <desc>".$row['description']."</desc> <thumb>".$row['thumb']."</thumb> <img>".$row['image']."</img> </image> "; } ?> Thanks James Hi all I have 3 tables Table_1, Table_2 and Table_3 Table_1 is a list of countries, with name and country_id Table_2 is a table that has 3 fields, id, name and description Table 3 is a table that has name, Table_2_id So what I need to do: Display the name and description field of Table_2 in a form Loop through the countries table and display each as an input box and display on the same form When I fill out the form details, the name/description must be inserted into Table_2, creating an id The input boxes data then also needs inserting into Table_3, with the foreign key of Table_2_id So a small example would be: Name: testing Description: this is a test Country of Australia: Hello Country of Zimbabwe: Welcome This means that in Table_2, I will have the following: ============================= | id | name | description | 1 | testing | this is a test ============================= Table_3 ============================= | Table_2_id | name | country_id | 1 | Hello | 20 | 1 | Welcome | 17 ============================= 20 is the country_id of Australia 17 is the country_id of Zimbabwe Code: Generating the input fields dynamically: $site_id = $this->settings['site_id']; $options = ''; $country_code = ''; $query = $DB->query("SELECT country_code, country_id, IF(country_code = '".$country_code."', '', '') AS sel FROM Table_1 WHERE site_id='".$this->settings['site_id']."' ORDER BY country_name ASC"); foreach ($query->result as $row) { $options .= '<label>' . 'Test for ' . $this->settings['countries'][$row['country_code']] . '</label>' . '<br />'; //$row['country_id'] is the country_id from Table_1 $options .= '<input style="width: 100%; height: 5%;" id="country_data" type="text" name="' . $row['country_id'] . '" value="GET_VALUE_FROM_DB" />' . '<br /><br />'; } echo $options; This outputs: Code: [Select] Textareas go here...... <label>Test for Australia</label> <input type="text" value="" name="20" id="country_data" style="width: 100%; height: 5%;"> <label>Test for Zimbabwe</label> <input type="text" value="" name="17" id="country_data" style="width: 100%; height: 5%;"> Now, I need to insert the value of the input field and it's country_id (20 or 17) into Table_3 and also Table_2_id. This then means I could get the value from Table_3 to populate 'GET_VALUE_FROM_DB' But I'm at a loss on how I'd do this. Could someone help me with this? Thanks I want to pull some records plus unique key from one mysql table and then use them as questions in a form/questionnaire. The post form will have six radio buttons to the right of the fields pulled with the key posted but hidden and will wirte to another table. I guess this is a templating question- as I've successfully retrieved the table 1 records via a query - I just can't seem to use them in the form. Below is the code I'm using to view table "PCM1" <?php // query.php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database) or die("Unable to select database: " . mysql_error()); $query = "SELECT * FROM pcm1"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j < $rows ; ++$j) { echo 'RID: ' . mysql_result($result,$j,'mcde') ; echo 'Statement: ' . mysql_result($result,$j,'oppclub') . '<br />'; ; } In brief, I'm attempting to capture the form data from a dynamic form to a mysql database. From he
To He
The post data looks like this from the form - Array(
... ) PHP CODE:
... As a non-php or mysql developer, I'm learning on the fly. This is a section of the php file that I was using to post the form data to mySQL. This worked great up to the point I added the dynamic form widget. <?php // This function will run within each post array including multi-dimensional arrays function ExtendedAddslash(&$params) { foreach ($params as &$var) { // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside. is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var); unset($var); } } // Initialize ExtendedAddslash() function for every $_POST variable ExtendedAddslash($_POST); $submission_id = $_POST['submission_id']; $formID =$_POST['formID']; $ip =$_POST['ip']; $fname =$_POST['fname']; $lname =$_POST['lname']; $spousename =$_POST['spousename']; $address =$_POST['address'][0]." ".$_POST['address'][1]." ".$_POST['address'][2]." ".$_POST['address'][3]." ".$_POST['address'][4]." ".$_POST['address'][5]; ... $db_host = 'localhost'; $db_username = 'xxxxx'; $db_password = 'xxxxx'; $db_name = 'xxxxx'; mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error()); mysql_select_db($db_name); // search submission ID $query = "SELECT * FROM `tableName` WHERE `submission_id` = '$submission_id'"; $sqlsearch = mysql_query($query); $resultcount = mysql_numrows($sqlsearch); if ($resultcount > 0) { mysql_query("UPDATE `tableName` SET `fname` = '$fname', `lname` = '$lname', `spousename` = '$spousename', `address` = '$address', WHERE `submission_id` = '$submission_id'") or die(mysql_error()); } else { mysql_query("INSERT INTO `tableName` (submission_id, formID, IP, fname, lname, spousename, address) VALUES ('$submission_id', '$formID', '$ip', '$fname', '$lname', '$spousename', '$address') ") or die(mysql_error()); } ?> It has been suggested that I explore using the PHP Explode() function. It's possible that may work, but can't get my head around how to apply the function to the PETLIST Array. Looking for suggestions or direction to find a solution for this challenge. Looking forward to any replies. Hi Folks,
Firstly I am new, I have read several topics here and learned a lot, I would class myself as 'slightly better than basic', but my knowledge is mostly gained from reading code.
I am making a simple POST form for work, the data gets inserted into MySQL, nice and easy, I can make it work if I write out the statement completely, BUT I need to make a new form, it will have HUNDREDS of input fields, I really don't want to write the code, and I figured programmatically is a good way to go anyway as forms change and new forms may be required, so I set about building a function to completely handle my post data, bind it to a statement and insert it into a table, I have scrapped it a half dozen times already because something fundamentally doesn't work, but I am very close! The function can write the statement, but I need to bind the POST values before I can insert, something going wrong here and I would appreciate some help, I have a feeling it's a problem with an array, but anyway I will show you what I have, give you some comments as to my reasoning, and hopefully you can help me with the last bit
public function getColumnNames($table){ $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; try { $stmt = $this->dbh->prepare($sql); $stmt->bindValue(':table', $table, PDO::PARAM_STR); $stmt->execute(); $output = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $output[] = $row['COLUMN_NAME']; } $all = array($output); $a1 = array_slice($output, 1); // I don't want column 1, it contains the ID, its auto incremented. $a2 = array_slice($a1, 0, -3); // I don't want the last 3 columns as they have default values $selected = array($a2); // contains all the columns except those excluded by array_slice, columns now match all of the input fields on the form foreach ($selected as $row){ $fields = "`" . implode('`, `', $row) . "`"; // I'm making `fields` here, $bind = ":" . implode(', :', $row); // And making :values here } return array ( "raw" => $all, "fields" => $fields, "bind" => $bind ); } catch(PDOException $pe) { trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR); } } public function addRecord(){ $col = array(); $col = $this->getColumnNames("table"); $raw = array($col['raw']); $fields = array($col['fields']); $bind = array($col['bind']); $columnList = implode('`, `', $fields); $paramList = implode(', ', $bind); $sql = "INSERT INTO `{$this->dbtable}` ($columnList) VALUES ($paramList)"; return $sql; // this returns something like: INSERT INTO `table` (`field1`, `field2`, `field3`) VALUES (:field1, :field2, :field3)";perfect I thought, now I just need to bind the values from $_POST... then I get stuck. Edited by luke3, 08 January 2015 - 12:10 PM. Hi I am new to development but really stumped by a problem i am having The below code gives no errors but does not populate the datebase with the infom Could anybody give me some pointers? <?php require "header.php"; ?> <main> <div class="wrapper-main"> <section class="section-default"> <h1>Signup</h1> <?php if (isset($_GET["error"])) { if ($_GET["error"] == "emptyfields") { echo '<p class="signuperror">Please Fill In All Fields!</p>'; } } ?> <form class="form-add" action="" method="post"> <label>Name</label><br> <input type="text" name="name" placeholder="name"><br> <LABEL>Gender</LABEL><br> <select name="gender"> <option value="">--Select--</option> <option value="Male">Male</option> <option value="Female">Female</option> </select><br> <input type="submit" name="insert" value="Insert Data"> </form> </section> </div> </main> <?php $dBServername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "loginsystemtut"; // Create connection $conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if (isset($_POST['insert'])) { $name = $_POST['name']; $gender = $_POST['gender']; $sql = ("INSERT INTO asdf (name, gender) values (?, ?)"); $stmt = mysqli_stmt_init($conn); mysqli_stmt_bind_param($stmt,"ss",$name,$gender); mysqli_stmt_execute($stmt); header("Location: ../loginsystem/permnew1.php?success"); exit(); } ?>
any help would be great Thanks Steve I get this error-->Notice: Undefined index: name in C:\wamp\www\sedit.php on line 13 Code: [Select] <?php session_start(); $db_handle = mysql_connect("localhost", "root", ""); $db_found = mysql_select_db("fouzan_db", $db_handle); if ($db_found) { echo "connected.<br/>"; if (isset($_POST['xyz'])) { $me = $_POST['text']; $sql="UPDATE `slogin` SET `data`='$me' WHERE username= '$_SESSION[name]'"; $result = mysql_query($sql); //to inform this is a query echo "Thank you for using our mail form"; } else { echo "<form method='post' action='sedit.php' /> Message:<br /> <textarea name='text' rows='15' cols='80'> </textarea><br /> <input type='submit'value='submit' name='xyz'/> </form>"; } } else { print "Database NOT Found "; mysql_close($db_handle); } ?> <html> <body> <head> </head> </body> </html> I have a form that is supposed to update a mysql row. The problem is that it wont post the $id to the script here is the form:form method="post" action=""> <label class="description" for="element_1">Payment Status: </label> <select class="element select medium" id="element_1" name="element_1"> <option value="Paid" SELECTED>Paid</option> <option value="Bill Sent" >Bill Sent</option> <option value="Check to be cashed" >Check to be cashed</option> </select> <input type="hidden" name="id" vlaue="<?php Print $ID; ?>"> <input id="saveForm" class="button_text" type="submit" name="payment" value="Update" /> </li> </ul><br><?php Print "Payment Status: <b>".$info['payment'] . "</b>"; ?> </form> here is the php side:if (isset($_POST['payment'])) { mysql_real_escape_string($insert = "INSERT INTO `YBK_Ads` (`payment`) VALUES ('{$_POST['element_1']}') WHERE `YBK_Ads`.`ID` = '".$_POST['id']."'"); mysql_query($insert) or die( 'Query string: ' . $insert . '<br />Produced an error: ' . mysql_error() . '<br />' ); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "<p>Thank you, the Payment status has been updated.</p>"; $error .="</span>"; setcookie('Errors', $error, time()+20); header('Location: /list.php'); exit; die; } ?> I'm getting this on post Code: [Select] Query string: INSERT INTO `YBK_Ads` (`payment`) VALUES ('Paid') WHERE `YBK_Ads`.`ID` = '' Produced an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `YBK_Ads`.`ID` = ''' at line 1its not putting anything in the ID value So i'm sending id value trough post in json format. When i open Firebug it returns the correct value but in php it's keep returning null. Code: [Select] $('.stars').bind('click', function() { var star = this; var data = {'q' : $(star).attr('id') }; $.ajax({ type:'post', url:"voting.php", data:data, dataType:'json' }); return false; }); Code: [Select] <?php $q=$_POST['q']; echo json_encode($q); ?> could someone help me with this code? It works fine without ip2long function? weird <form method="post" action="test.php"> <textarea name="new" cols="40" rows="10"> samplehost-1,127.0.0.1 samplehost-2,127.0.0.2 </textarea><br> <input type="submit" value="Add Servers"> </form> if(isset($_POST['new'])) { $array= explode("\n",$_POST['new']); foreach ($array as $ni) { $array=explode(',', $ni); echo ip2long($array[1]); } } This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=349304.0 Hi, i'm currently building essentially an API for my URL shortener site so other sites can implement it. But i've hit a stumbling block on the last script of the lot(the others merely collate the data and store it) In this last script, i need to find all this data, stored in cookies and inout it into the database, as the main site does(i'm confident this bit works, as it's the code from the main site just copied across, and i can see the data in the database). Importantly, i then need o look in another table for the callback URL to send the data back to $urltoshorten = $_COOKIE["URLtoShorten"]; $alias = $_COOKIE["urlalias"]; $key = $_COOKIE["key"]; //connection details go in here $alias =mysql_real_escape_string($alias); $urltoshorten = mysql_real_escape_string($urltoshorten); $base = "http://s-url.co.uk/i/?id="; $url = $base . $alias ; //this is the main bit, where the URL shortening occurs mysql_query("INSERT INTO table (id, name) VALUES('$alias', '$urltoshorten')")or die( mysql_error()); //this is where the callback url is looked for $result= mysql_query("SELECT apiaddress FROM apistuff WHERE apinumber='$key'")or die( mysql_error()); $row = mysql_fetch_array($result); $new = $row[apiaddress]; //I then start a CURL session to POST data to the page in question, as found above $Curl_Session = curl_init($new); curl_setopt ($Curl_Session, CURLOPT_POST, 1); curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "shortenedurl=$url"); curl_exec ($Curl_Session); curl_close ($Curl_Session); annoyingly, no errors get thrown, as far as i can see, i just end at a blank page without being returned to the callback page. I'm rather stumped on this one, where am i likely to be going wrong/how do i go about correcting it. Cheers Joe I am having trouble with passing values with a POST to another php file. I am getting the error : undefined index : productID and undefined index: filename. I have also tried : <form method = \"POST?pdib=$processID&filename=$filename\" action = \"upload2.php\" > When I look at the array of superglobals, they are both defined. Thank you! Here is the code : drawfirsttwoforms: $sql = "SELECT ProductFilename, ProductName, ProductID, ProductDescription,ProductCost,ProductQuantity, ProductCatTitle FROM products INNER JOIN customers ON customers.CustomerID = products.CustomerID WHERE ((products.ProductKeyWord1 = ?) OR (products.ProductKeyWord2 = ?) OR (products.ProductKeyWord3 = ? )) AND (products.ProductCatTitle = ?) "; $stmt = $dbo->prepare($sql); $stmt->bindParam(1, $keyword1); $stmt->bindParam(2, $keyword1); $stmt->bindParam(3, $keyword1); $stmt->bindParam(4, $titleOfSelectedDropDown); $stmt->execute(); while ($row = $stmt->fetch()) { //these variables do have values here $productID = $row['ProductID']; $filename = $row['ProductFilename']; $string1 .= " <div class = \"A\" id = \"$mainDiv\"> <p id = \"link1\">product id :$productID</p> <p>category id :$category</p> <div class = \"A\" id = \"endz\"></div> <div class = \"A\" id = \"startz\"></div> <div class=\"container\"> <div id = \"testing\" >testing <div> <div id = \"$displayID\" > </div> <div class=\"row\" > <div class=\"col\"> <form method = \"POST\" action = \"upload2.php\" > <input type=hidden id='$productID' name= '$productID' value=\"A\"> <input type=hidden id=\"$filename\" name=$filename value=\"B\"> <button value = \"Submit\" type = \"submit\" >submit it</button> </form> <iframe id=\"upload_target\" name=\"upload_target\" style=\"width:0;height:0;border:0px solid #fff;\"></iframe> <img width=\"120\" height =\"120\" id = \"$imageID\" src=\"../php proj/uploads/$filename?<?php echo filemtime($filename)?>\"> <button onclick = \"imageRefresh( '{$filename}', '{$imageID}', '{$_SESSION["msg"]}' )\" >Display</button> </div> AFTER: if (!isset($myObj) && isset($string1)) { $myObj = new stdClass(); $myObj->htmlstuff = $string1; //Encode the data as a JSON string $jsonStr = json_encode($myObj); echo $jsonStr; }
function printHTML1(keyword){ const element = document.getElementById("dropDown1"); //const checkValue = element.options[element.selectedIndex].value; const checkText = element.options[element.selectedIndex].text; var val1 = checkText; var xmlhttp = new XMLHttpRequest(); var keyword1 = keyword; var url = "drawfirsttwoforms.php?keyword=" + keyword.value + "&" + "val1=" + val1; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var jsonData = JSON.parse(this.responseText); var answerHtml = jsonData.htmlstuff; document.getElementById("codehere").innerHTML = answerHtml; createAndModifyDivs(); } }; xmlhttp.open("GET", url , true); xmlhttp.send(); }
upload2.php <?php session_start(); $productID = $_POST['productID']; $filename = $_POST['filename'];
I have a problem about Blog Post Categorization Script. Can anyone review it ? Instead of showing how much posts that category have it just repeats. Code: [Select] <? $sqlCategories = "SELECT * FROM blog_entry, categories where blog_entry.CategoryID=categories.CategoryID and blog_entry.UserID=".$_REQUEST['UserID']." order by Category asc"; $resultCategories = mysql_query($sqlCategories, $conn); if (@mysql_num_rows($resultCategories)!=0){ $strcategory=""; while($row_categories = @mysql_fetch_array($resultCategories)) { $categoryduplicate=0; $arrcat = explode(",",$strcategory); for($i=0;$i<strlen($arrcat);$i++) { if($arrcat[$i]==$row_categories['CategoryID']) { $categoryduplicate=1; } } if($categoryduplicate==0) { if($strcategory=="") { $strcategory=$row_categories['CategoryID']; } else { $strcategory=$strcategory.",".$row_categories['CategoryID']; } $sqlCategories2 = "SELECT * FROM blog_entry where CategoryID=".$row_categories['CategoryID']." and UserID=".$_REQUEST['UserID']; $resultCategories2 = mysql_query($sqlCategories2, $conn); if($row_categories['CategoryID'] == $_REQUEST['CategoryID']) { echo " <Tr> <td class='content'><a href='postss.php?CategoryID=".$row_categories['CategoryID']."&UserID=".$_REQUEST['UserID']."&Category=".$row_categories['Category']."' class='in_sel'>".$row_categories['Category']."</a> [".@mysql_num_rows($resultCategories2)."]</td> </Tr> "; } else { echo " <Tr> <td class='content'><a href='posts.php?CategoryID=".$row_categories['CategoryID']."&UserID=".$_REQUEST['UserID']."&Category=".$row_categories['Category']."' class='in_sel'>".$row_categories['Category']."</a> [".@mysql_num_rows($resultCategories2)."]</td> </Tr> "; } } } } ?> |