0I have three arrays... example:
phonenums
[0] 555-5555
[1] 555-4444
[2] 555-3333
types
[0] cell
[1] home
[2] work
notes
[0] a note
[1] the babysitters name
[2] call before 6pm
They come from a form with dynamically added inputs, so the number of rows is arbitrary.
I want to put these arrays into a table in MySQL, using PHP
Table name: customerphones
id
customer_id
phone
type
notes
I can get any single array into the database fine, but, when it comes to putting in all three to coordinate with each other (ex: each row[0] to be in one row of the database table)....I'm stuck! I keep rewriting it in different loops or whatnot, and it comes out wrong every time.
I can post my code if it helps explain my situation further. I am just looking for a "concept" here though, to point me in the right direction.
Should I combine the arrays somehow?, or put them into a loop? I don't know!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is my solution I came up with (as requested). I'm sure it is not practical at all...and there is probably a much better way to do it. But it got my desired result.
// ~~~ Get variables from the form submitted
$phonenums = $_POST["phone"];
$types = $_POST["type"];
$notes = $_POST["notes"];
// ~~~ Queries for Inserting Customer Phone Numbers
$querynum = "INSERT INTO customerphones";
$querynum .= "(customer_id, phone)";
$querynum .= "VALUES (?, ?)";
$stmtnum = mysqli_prepare($db, $querynum);
$queryty = "UPDATE customerphones SET ";
$queryty .= "type = ? ";
$queryty .= "WHERE customer_id = ? AND phone = ?";
$stmtty = mysqli_prepare($db, $queryty);
$queryno = "UPDATE customerphones SET ";
$queryno .= "notes = ? ";
$queryno .= "WHERE customer_id = ? AND phone = ?";
$stmtno = mysqli_prepare($db, $queryno);
// Loops for executing the queries to insert phone numbers
// (I scraped this together b/c I couldn't get other methods to work...Change this later)
$n = 0;
foreach($phonenums as $rowph) {
mysqli_stmt_bind_param($stmtnum, 'is', $custid, $rowph);
mysqli_execute($stmtnum);
$rct = 0;
foreach($types as $rowty) {
if($rct == 0) {
$x = $types[$n];
mysqli_stmt_bind_param($stmtty, 'sis', $x, $custid, $rowph);
mysqli_execute($stmtty);
$rct++;
}
} // End Update Phone Type
$rct = 0;
foreach($notes as $rowno) {
if($rct == 0) {
$x = $notes[$n];
mysqli_stmt_bind_param($stmtno, 'sis', $x, $custid, $rowph);
mysqli_execute($stmtno);
$rct++;
}
} // End Update Phone Notes
$n++;
} // End foreach loops
Well, I'm gonna take a shot in the dark here.
Using PDO with PreparedStatements, MultipleIterator and ArrayIterator:
$dbh = new PDO("mysql:host=localhost;dbname=YOUR_DATABASE;", "root", "");
$sth = $dbh->prepare("INSERT INTO customerphones(phone, type, notes) VALUES(:phone, :type, :note)");
$m = new MultipleIterator();
$m->attachIterator(new ArrayIterator($phonenums), 'phones');
$m->attachIterator(new ArrayIterator($types), 'types');
$m->attachIterator(new ArrayIterator($notes), 'notes');
foreach($m as $row){
$sth->bindParam(":phone", $row[0]);
$sth->bindParam(":type", $row[1]);
$sth->bindParam(":note", $row[2]);
$sth->execute();
}
I'm assuming that you're using a local MySQL server, and your server's root account isn't password protected.
This works like this:
Create a new PDO connection with some parameters;
Prepare a statement with some placeholders for an insert;
Create an Iterator to unite the arrays;
Attach all the arrays to the iterator;
Go through all the iterations of the iterator: Every iteration returns a array with a phone number, a type and a note;
Bind all the elements of the current iteration to the placeholders of the statement and then execute it.
But please post what you're using to connect to the DB, then I'll refactor my answer.
using mysqli:
$host = 'your_host';
$user = 'your_user';
$pass = 'your_pass';
$db = 'your_database';
$mysqli = new mysqli($host, $user, $pass, $db);
// Check connection mysql
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$sql = 'INSERT INTO customerphones(phone, type, notes) VALUES(?,?,?)';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sss', $phone, $type, $note);
$index = 0;
while(COUNT($phonenums) - 1 >= $index){
$phone = $phonenums[$index];
$type = $type[$index];
$note= $note[$index];
$stmt->execute();
$index++;
}
Related
I have a '^' separated list of product ID numbers, and I need to get just the product ID number, and then use it to query a SQL database. The product ID numbers are stored in the $_SESSION hash. For example:
SKUS: jpn18726^gr172645^123746^17246^eu186726^...
The code I can think of is something like this:
$prodmat = $_SESSION["product"];
if(preg_match("(\d+)(^\s*\d+)*", $prodmat) {
$stmt = "select shipcode from materials where material='???'";
}
Basically, I want to extract the product ID numbers from the '^' separated list, and then use the product ID numbers to query the DB.
Just do some explosions:
$prod_list = 'SKUS: jpn18726^gr172645^123746^17246^eu186726';
$list_parts = explode(':', $prod_list); // separate the text
$prods = explode('^', trim($list_parts[1])); // trim and put the list in an array
print_r($prods);
Result:
Array
(
[0] => jpn18726
[1] => gr172645
[2] => 123746
[3] => 17246
[4] => eu186726
)
Now you can loop through the array with your query.
foreach($prods as $product) {
$sql = "SELECT foo, bar, WHERE products WHERE id = ?";
// bind the current product
// do the query
}
You should be performing just one query if possible. If you are using mysqli, you can use the following code block, though I'll recommend pdo because it is easier when dealing with a variable number of placeholders.
This code does NOTHING to validate the input data. It assumes that your SESSION data is 100% trustworthy and reliably formatted. If you need to validate, then you will want regex to do the validating. ...perhaps something like ~^SKUS: [a-z\d]+(?:\^[a-z\d]+)*$~ if your ids only contain numbers and letters.
Code:
if (!empty($_SESSION["product"])) {
// $_SESSION["product"] = 'SKUS: jpn18726^gr172645^123746^17246^eu186726';
// "SKUS: " is fixed/constant, so just remove it by known substring position/length
$params = explode('^', substr($_SESSION["product"],6)); // trim off leading substring BEFORE exploding
$count = count($params);
$csph = implode(',', array_fill(0, $count, '?')); // comma-separated placeholders
if(!$stmt = $conn->prepare("SELECT `shipcode` FROM `materials` WHERE `material` IN ($csph);")){
echo "Syntax Error # prepare: " , $conn->error; // do not echo error on public site
}else{
array_unshift($params, str_repeat('s', $count)); // prepend the type values string
$ref = []; // add references
foreach ($params as $i => $v) {
$ref[$i] = &$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt, 'bind_param'], $ref);
if (!$stmt->execute()) {
echo "Error # bind_param/execute: " , $stmt->error; // do not echo error on public site
} elseif (!$stmt->bind_result($shipcode)) {
echo "Error # bind_result: " , $stmt->error; // do not echo error on public site
} else {
while ($stmt->fetch()) {
// do something with $shipcode
}
$stmt->close();
}
}
} else {
echo "Missing/Invalid product data";
}
If you need to identify your shipcodes with the corresponding id, then just add the material column to the SELECT clause and the bind_result() call.
All that said, if you can confidently validate/sanitize your SESSION data, you can avoid the convolution of a prepared statement and just write your SELECT query with IN in the WHERE clause like: WHERE materials IN (' . implode("','", $params) . ').
I have a JSON string coming into a PHP file from JS/AJAX. The number of entries is dynamic, ranging from 6 to 30.
I populate an array as follow
$myarray = array();
$dataLength= count($decodedJSON['make'][0]['model'][0]['color']);
for ($x = 0; $x < $dataLength*2; $x+=2) {
$myarray[$x] = $decodedJSON['make'][0]['model'][0]['color'][$x/2]['int'];
$myarray[$x+1] = $decodedJSON['make'][0]['model'][0]['color'][$x/2]['ext'];
}
for ($x = $dataLength*2; $x < 30; $x++) {
$myarray[$x] = 0;
}
So this basically gives me an array that is end-padded with zeros with my data at the front.
Now, I want to insert this into my SQL table that has that maximum number of column
$sql = "INSERT INTO cars VALUES ( '$dataLength', '$myarray[0]', '$myarray[1]', '$myarray[2]', '$myarray[3]', '$myarray[4]', '$myarray[5]', '$myarray[6]', '$myarray[7]', '$myarray[8]', '$myarray[9]', '$myarray[10]', '$myarray[11]', '$myarray[12]', '$myarray[13]', '$myarray[14]', '$myarray[15]', '$myarray[16]', '$myarray[17]', '$myarray[18]', '$myarray[19]', '$myarray[20]', '$myarray[21]', '$myarray[22]', '$myarray[23]', '$myarray[24]', '$myarray[25]', '$myarray[26]', '$myarray[27]', '$myarray[28]', '$myarray[29]', 42)";
but I'm thinking there must be a better way???
Thanks for any help,
HSC.
Why don't fill the array with zeros when you declare it; then you can save the last loop:
$myarray =array_fill(0,30,0);
If you are using PDO you could simple things up like this:
try {
$pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database, $user, $pass, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}catch(PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
exit;
}
$sql = 'INSERT INTO cars VALUES ('.implode(',',array_fill(0,30,'?')).')';
$values = array_fill(0,30, null);
/** populate array with data here ... **/
$stmt = $pdo->prepare($sql);
try {
$stmt->execute($values);
}catch(PDOException $e) {
die($e->getMessage());
}
A sidenote here, it would be better if you could determine which columns are required to do the insert, you could alter your JSON to match the column with the value. This way you would prevent the overhead of always have to define the 30 columns and you just could assign a default value the column
Here I'm trying to insert the datas again into database new table (with quantity & customer details). $grocery_id and $grocery_item values are fetch from database. $customername, $customermobile, $groqty values are user will enter the details in that appropriate textfield.
When I execute this code ($groceryid, $groceryitem) -> These two column always stored the last row values. Because I've put the query outside of foreach loop. Here is my problem. If I put the query inside the foreach it works fine. But, quantity values doesn't work properly. So, How can I execute the query properly (outside of foreach loop)?
<?php
if(isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
$customername = $_POST['customername'];
$customermobile = $_POST['customermobile'];
$groqty = $_POST['groceryquantity'];
for($i = 0; $i < sizeof($groqty); $i++)
{
$groqtys = $groqty[$i];
foreach($grocery_id as $key => $index_id )
{
}
$sql = "INSERT INTO ".customer_order." SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqtys' ";
mysql_query($sql,$CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
You could simply use one foreach loop considering the index values of $grocery_id and $groqty are the same.
Try:
<?php
if (isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
// sanitizing your values
$customername = mysql_real_escape_string($_POST['customername']);
$customermobile = mysql_real_escape_string($_POST['customermobile']);
$groqty = array_map('mysql_real_escape_string', $_POST['groceryquantity']);
foreach($grocery_id as $key => $index_id)
{
$sql = "INSERT INTO " . customer_order . " SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqty[$key]' ";
mysql_query($sql, $CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
Also note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I hope my title isn't completely confusing. I'd like to start by saying I am in now way a programmer and am an amateur with PHP and MySQL, which I use for online gaming. I have been tirelessly working at this for a few days, with no success. I've been toying with the idea of asking for help here, hoping folks go easy on me and don't completely rip apart my code! Like I said, I'm an amateur.
Basically, what I'm trying to do is match the $horsename data from my $_POST array with name in my table called horses. If they do not match it will add a horse with that name into the horses table. If they do match, it will simply continue on and add the data from the $_POST array into the results table for each line.
The issue I'm getting, (and I've toyed with this multiple times, with a different issue arising each time) is even if the $horsename matches name in the horses table, it tries to add a new horse into the horses table. It also is not moving onto the next line of data and will try to add the same horse over and over again. (Hope that makes sense!)
I'm pasting most of my code from this page below, just in case it's something earlier in my code causing this issue. Please note, a portion of this code is not my own and I am working on it for someone else, so if things are not completely uniform in a couple of spots, that is why. The portion I'm working on is what I've mentioned above.
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$results = str_replace("\r", '', trim($_POST['news']));
$data = array();
$lines = explode("\n", $results);
foreach ($lines as $place) {
if (!empty($place)) {
$data = array();
$detail = explode(",", $place);
if (!empty($detail)) {
$id = '';
$show = $_POST['show'];
$year = $_POST['year'];
$association = $_POST['association'];
$chpoints = $_POST['chpoints'];
$rchpoints = $_POST['rchpoints'];
$ttpoints = $_POST['ttpoints'];
$chearnings = $_POST['chearnings'];
$rchearnings = $_POST['rchearnings'];
$ttearnings = $_POST['ttearnings'];
$horsename = stripslashes(trim($detail[0]));
$placement = stripslashes(trim($detail[1]));
$class = stripslashes(trim($detail[2]));
if($placement === 'CH'){
$points = $chpoints;
}
else if ($placement === 'RCH') {
$points = $rchpoints;
}
else {
$points = $ttpoints;
}
if ($placement === 'CH') {
$earnings = $chearnings;
}
else if ($placement === 'RCH') {
$earnings = $rchearnings;
}
else {
$earnings = $ttearnings;
}
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
if (isset($_POST['news'])) {
$query="INSERT INTO `results` (`id`, `show`, `year`, `place`, `name`, `class`, `points`)
VALUES ('$id','$show','$year','$placement','$horsename','$class','$points')";
mysql_query($query) or die ('Error updating database: ' . mysql_error());
echo "Result successfully added!" ;
}
};
};
};
To take a snip-it from above, this is the place I'm having the issues:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
If anything from the page where news is coming from is needed, please let me know.
Thanks in advance!
The problem is that you are querying the database for a list of every horse name. You're iterating through that list and each time the names don't match, you're inserting the new name. What you need to do instead is to query for the specific name.
SELECT * FROM horses WHERE name = '$horsename'
If this returns a row, then you know the horse is already in the database. If it returns no rows, then you can safely insert once. By the way, you'll want to properly escape your input to prevent SQL injections so don't use my code verbatim.
Try this:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
$i = 0;
$horsename = "";
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
$i = 1;
}
}
if($i == 1) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
I know there isn't enough validation in here just going through some testing. $result always returns empty? Is my query bad? I'm new to PHP and concatenating variables into strings is not something I have grasped full. Going with the OOP form since I'm pretty familiar with it and the concepts.
Also, I know this code is terribly sloppy... just trying to dive right in =)
`
$page = new Page();
$page->title = "Add a New Item";
$page->DisplayHeader();
$page->DisplaySidebar();
if (isset($_POST['submit']))
{
// make short variable names
$name = trim($_POST['name']);
$level = intval($_POST['level']);
$slot = strtolower($_POST['slot']);
$hp = intval($_POST['hp']);
$mana = intval($_POST['mana']);
$mvs = intval($_POST['mvs']);
$int = intval($_POST['int']);
$wis = intval($_POST['wis']);
$str = intval($_POST['str']);
$dex = intval($_POST['dex']);
$con = intval($_POST['con']);
$p_ac = intval($_POST['p_ac']);
$m_ac = intval($_POST['m_ac']);
$saves = intval($_POST['saves']);
$hit = intval($_POST['hit']);
$dam = intval($_POST['dam']);
$queryOk = 1;
if (empty($name) || empty($level) || empty($slot))
{
echo '<h3>Please enter all the required fields</h3>';
$queryOk = 0;
}
// Instantiate database object and connect
# $db = new mysqli('*host*', '*user*', '*pass*', '*database*');
// Check connection to
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database, try again later';
}
$query = "INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)".
"V ALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
$result = $db->query($query);
if (!$result)
{
echo '<h3>Error: Item was not entered. (Your webmaster sucks)</h3>';
}
else {
echo "<p>The items \"$name\" was successfully entered into the database. <a href=\"equipment.php\>Back to Equipment or add another item.</a></p>";
}
$db->close();
}`
If the space in V ALUES is actually in your code that would cause your query to fail
UPDATE
If that isn't the cause of the error use $mysqli->error to see what error occurred.
if (!$result)
{
echo '<h3>'$mysqli->error' (Your webmaster sucks)</h3>';
}
int is a reserved word in mysql, and you're using it as a fieldname. You'll have to escape it with backticks:
INSERT INTO ... (..., `int`, ...)
^---^-- escapes
your query:
INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)
^^^^--- problem here
VALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
^^^^^---NOT here