Exploding input from text area and looping through 2 arrays - php

I'm entering a list of numbers in two text areas. One area is known as SectionID and the other Length. Both are of equal length. I'm submitting these to a PHP handling page which enter details to an SQL db.
<?PHP
$exchange = $_POST['Exchange'];
$estimate = $_POST['Estimate'];
$sectionid = $_POST['SectionID'];
$length = $_POST['Length'];
$username = "USER";
$password = "PASS";
$hostname = "HOST";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATAB", $con) or die("Could not select examples");
$sectionid = explode("\n", str_replace("\r", "", $sectionid));
$length = explode("\n", str_replace("\r", "", $length));
foreach ($sectionid as $key => $secdata) {
$lendata = $length[$key];
$query = "INSERT INTO table (Exchange, Estimate, SectionID, Length) VALUES ('$exchange','$estimate','$secdata','$lendata')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "$estimate created on $exchange Exchange!";
mysql_close($con);
?>
This for some reason isn't working and I just can't see my mistake. Never before have I had to do this. The current result makes 1 entry only to the db, leaves the SectionID blank and fills Length with multiple lines from the text area.
What I'm trying to achieve is create as many entries as there are SectionID's in the list and insert the SectionID and Length that correspond to each other. This is not my only attempt, I have used about4 different variations of exploding the $_POST.
Anyone care to help me out?

No problem with explode or anything related to textarea value. its a SQL Syntax error
try this
$query = "INSERT INTO `table` (`Exchange`, `Estimate`, `SectionID`, `Length`) VALUES('$exchange','$estimate','$secdata','$lendata')";
you may enable php error display now.

To debug your code, try
print_r($sectionid);
foreach ($sectionid as $key => $secdata) {
$lendata = $length[$key];
print '<br />row '.$key . ':{'.$secdata.'}';
$query = "INSERT INTO table (Exchange, Estimate, SectionID, Length) VALUES ('$exchange','$estimate','$secdata','$lendata')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
If the data is being received and parsed correctly, you should see on your screen the initial array printed to the screen along with each variable within the array printed on seperate lines surrounded by brackets.
If you see something like
row 0: {}
Then it means you arent parsing or receiving the data correctly. Check that you are posting sectionID and not sectionid (upper/lower variance with the "id" part).

Related

UPDATE to current date (PHP)

im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());

How to store data into multiple MySQL tables according to the checkbox value?

I have an html form, with multiple checkboxes (subjects)
When a user (student) selects the subjects ,the StudentID is stored in a MySQL table along with the selections made in separate columns but in the same table.
My question is: How can I store the student ID in a new table if the checkbox value "equals" to something, would strpos do it ?
for example:
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
}
Full Code:
<?php
$host = 'localhost';
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
$tbl_name="courses" ;
$tbl_name="studentinfo";
$tbl_name="newtable";
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
mysqli_set_charset($dbcon, "utf8");
if (!$dbcon) {
die('error connecting to database'); }
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courses){
$cc=$cc. $courses.',';
}
}
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
echo "$cc, trtue";
}
HTML
<form action="cdb.php" method="get">
<input name="studentid" type="text" id="studentid" maxlength="11"value="Student ID" />
<input type="checkbox" name="ckb[]" value="251000-1"/>
<input type="checkbox" name="ckb[]" value="251000-2"/>
Ok if you absolutely must ignore all good database design practices try this.
Instead of creating a comma delimited list and putting it into the newtable use the serialize() function to place the contents of $_GET['ckb'] into this new row. At least this way you can use unserialize() to get back an array which makes manipulating the data easier even if it does not make searching the database any easier.
You could replace serialise/unserialize with json_encode() and json_decode()
references:
serialize: http://php.net/manual/en/function.serialize.php
unserialize: http://php.net/manual/en/function.unserialize.php
<?php
$host = 'localhost';
// I assume you moved apache to port 8889.
// so its irrelevant to mysql connection,
// good job you are not actually using this variable anywhere
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
// fix so you have 3 variables and are not overwriting the same one
$tbl_name1="courses" ;
$tbl_name2="studentinfo";
$tbl_name3="newtable";
// remove unnecessary double quotes
$dbcon = mysqli_connect($host,$username,$password,$db_name) ;
// add some error checking that reports the actual error
if ( ! $dbcon ) {
echo 'Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error();
exit;
}
mysqli_set_charset($dbcon, "utf8");
if(isset($_GET['ckb'])) {
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$cc = serialize($_GET['ckb']);
$result = mysqli_query($dbcon,"INSERT INTO newtable
(studentid,ckb)
VALUES ('$studentid','$cc')");
if ( ! $result ) {
echo mysqli_error($dbcon);
exit;
}
}
?>
Below, total size of 'ckb' checkbox is calculated. Then. due to for loop, it will run till the total size. 'studentid' coming from the textbox. It will insert into the table till for loop condition is true.
extract($_POST);
$CKBsize=sizeof($ckb);
for($i=0;$i<$CKBsize;$i++)
{
$CourseName=$ckb[$i];
mysql_query("INSERT INTO newtable SET studentid='$studentid', ckb='$CourseName'");
}
It turns out , that using this code does in fact sort the data according to the checkbox in new and different tables
if (strpos($cc,'251000') !== false) {
$sql3="INSERT INTO newtable (studentid, ckb)
VALUES ('$studentid', '$cc')";
echo 'true';
}
However It seems I must check for the sql3 statement
if (!mysqli_query($dbcon,$sql3))
{
die('Error: ' . mysqli_error($dbcon));
}
Another mistake I had was using reserved words such as table in one of the sql statements. that fixed and the code above added solved the problem.

Using PHP to redirect when SQL query comes up empty

I am using this PHP script to return search input values with corresponding URL values on a MySQL database/table. The idea is to append them to a redirect to automatically jump to that page.
<?php
$searchResults = $_POST['search'];
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT url
FROM Table_1
WHERE input = '" .$searchResults."'";
mysql_select_db('database_1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$redirect = $row['url'];
header('Location:'.$redirect);
}
To catch any input that does not match a value on Table_1 added this If statement. It will take any non relevant or misspelled inputs and redirect them to xyz.html
if (mysql_num_rows($retval) < 1) {
header('Location: xyz.html');
}
Is this incorrect? It seems to be working but I assume there must be a cleaner way of doing this/ it may be bad practice.
If you are expecting only one result from the query then it would work.
But if there are multiple rows then the last row would be loaded . It would be inefficient then.
You could also directly do this:
if($retval)
{ .$row = mysql_fetch_array($retval, MYSQL_ASSOC);
header('Location:'.$row);
}
else
header('Location:xyz.html');
You wouldn't need to use the while loop if you are expecting only one row.
The way you use is wrong, it may cause lots of headache.
2 ways :
1.If result is x then redirect to page A.
2.If result is x then load view just similar like page A with same header ,footer.
So , as per 2nd way ,when the query is empty , Load specific view which you want.
For your example , suppose you visit a Shopping cart Site, you clicked on Shoes category , if there is no shoes, the page shows message Sorry stock is empty, no shoes, it does not redirect you to any page if stock if empty.

Beginner MySQL database search - not getting results

I am having my first attempts to a search engine:
I have a database called "global" and a table called "mpl" which contains 11 columns (Named: Customer, Part No, Descripton, Country Of Origin, and several other) with multiple rows for parts.
What i aim to do with the code below - is to get the Description and Country Of Origin displayed for the Part No the user has entered to the search field.
Form:
<form action="search.php" method="post">
<input type="text" name="find" /><br />
<input type="submit" value="Search" /> </form>
And the PHP:
$host = "localhost";
$dbuser = "root";
$dbpass = " ";
$db = "global";
$con = mysql_connect($host, $dbuser, $dbpass);
if(!$con){ die(mysql_error());
}
$select = mysql_select_db($db, $con);
if(!$select){ die(mysql_error());
}
$item = $_REQUEST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
while($row = mysql_fetch_array($data)){
echo $row['Description']. "<br>";
echo $row['Country Of Origin']. "<br><p>";
}
?>
Can someone tell me what am i doing wrong? Once i enter anything to my form 'find' - i get no results. If i run the search using LIKE instead of "=" with no value - it displays a bunch of Descriptions and Country of origin - this means i have connected to my DB correctly. This is driving me nuts..I feel i have messed up the mysql_query() part somehow - but i can't figure out which part.
You are using the wrong characters to escape the Part No column name in your query. Escape them with the backticks (`) and it should be fine.
$data = mysql_query("SELECT * FROM mpl WHERE `Part No` ='".$item."'");
Also, you should validate the user's query to prevent SQL injection.
A lot of people here have already pointed out possible and actual errors in your code, but here's the combined solution. Firstly I converted your code to mysqli which is the correct way of connecting to a mySQL database. The way you were connecting is out of date, and not recommended. Secondly I added some code to stop sql injection. Thirdly, I changed 'Part No' to `Part No``(ignore the second back tick) in your query.
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'global');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$item = $mysqli->real_escape_string($_POST['find']);
/* query database */
$result = $mysqli->query("SELECT * FROM `mpl` WHERE `Part No` = '".$item."'");
while ($col = $result->fetch_array(MYSQLI_ASSOC))
echo '<p>' . $col['Description'] . '<br />' . $col['Country Of Origin'] . '</p>';
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
What if you change:
$item = $_REQUEST['find'];
to
$item = $_POST['find'];
Also some function like mysql_select_db() are deprecated and going to be removed. See:
http://php.net/manual/en/function.mysql-select-db.php
Try changing this potion.
$item = $_REQUEST['find']; $data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
to this
$item = $_POST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE Part No ='$item'");
do something like this in your request to remove any possible whitespaces and normalize to upper case for select string.
$item = strtoupper(trim($_REQUEST['find']));
And do this in your SQL: to normalize as well.
$data = mysql_query("SELECT * FROM mpl WHERE UPPER(TRIM('Part No')) ='".$item."'");
You are basically not getting an exact match on your where clause
First off, I agree with Quentin; you should be using a database API like PDO or Mysqli. Secondly, it looks like people can search for parts by their part numbers or descriptions. Assuming the part numbers are numeric and the descriptions are strings... check the type of input and run the query accordingly.
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "global";
// Establish a database connection and select one.
// Try using one of the database API's.
// Then compose your sql by checking for the type of input from the form.
// Since your request method is a POST, then just look in the `_POST` superglobal.
$item = $_POST['find'];
if( is_numeric($item) ){
$sql = "SELECT * FROM mpl WHERE 'Part No' = {$item}";
}else{
$sql = "SELECT * FROM mpl WHERE 'Description' LIKE '%{$item}%'";
}
// Then perform the query.

Display MySQL Database as an array

I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table

Categories