I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
I'm trying to work something out but I just can't get it to work. I need to do the following:
Pull data from a MySQL Table
Store that data in an array
Use that data from the array in a Function.
Current code looks like this (currently pulls data from MySQL Table and iterates over it, putting it in a table (purely to check it worked).
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("*****") or die(mysql_error());
$data = mysql_query("SELECT batch FROM widgetBatches") or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data )) { Print "<tr>";
Print "<th>Batch:</th> <td>".$info['batch'] . "</td> ";
Print "" . " </td></tr>";
} Print "</table>";
Here's the function, $widgetBatches needs to take the array from the previous code however nothing i've tried works. (there is more to the Widget() however it's not relevant to this issue. Thanks in advance!
$uI = 550;
Widget($uI);
function Widget($input) {
$currentValue = $input;
$i = 0;
$widgetBatches = [250, 500, 1000, 2000];
while ($currentValue > 0) {
$i++;
echo "Batch Number " . $i . "<br/>";
echo "Widgets Left To Fulfill Order: " . $currentValue . "<br/>";
$closest = ClosestBatch($widgetBatches, $currentValue);
echo "Closest Batch Available: " . $closest . "<br/>";
$currentValue = $currentValue - $closest;
echo "Remaining Widgets: " . abs($currentValue) . "<hr/>";
}
echo "<br />";
}
This is my array:
When I used mysqli_query in a different script, this style worked:
while ($printTest = mysqli_fetch_array($results)) {
echo $printTest['id'] . "<br />";
echo $printTest['questions'] . "<br />";
echo $printTest['answers'] . "<br />";
}
I can't figure out how to do the same thing with a PDO created array. With PDO, I can use foreach, like this:
foreach ($queryRows as $test=>questions){
echo $test;
}
Unfortunately, that doesn't give me access to id and answers in the same loop - which is important to me.
This is how I'm getting my PDO-generated array, currently:
$queryRows = $this->dbh->query("SELECT id, questions, answers FROM qarows WHERE usr = '$this->username'");
$queryRows = $queryRows->fetchAll(PDO::FETCH_ASSOC);
How do I access all 3 columns of my array, in a loop?
It's still the same fetch rows from db. Its still the same multi dimensional structure:
$select = $this->dbh->prepare('SELECT id, questions, answers FROM qarows WHERE usr = :usr');
$select->bindParam(':usr', $this->username);
$select->execute();
$queryRows = $select->fetchAll(PDO::FETCH_ASSOC);
foreach ($queryRows as $questions){
echo $questions['id'] . '<br/>';
}
Or the look a like mysqli:
$select = $this->dbh->prepare('SELECT id, questions, answers FROM qarows WHERE usr = :usr');
$select->bindParam(':usr', $this->username);
$select->execute();
while($printTest = $select->fetch(PDO::FETCH_ASSOC)) {
echo $printTest['id'] . "<br />";
echo $printTest['questions'] . "<br />";
echo $printTest['answers'] . "<br />";
}
I have a user table that contain a lots more data, I wonder how can I improve my select code below
if ($result = $db->query("SELECT * FROM user ")) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row["name"] . "<br />";
echo $row["user_id"] . "<br />";
echo $row["photo"] . "<br />";
//.. a lot more column here
}
}
I use this as a array: $user_info = mysql_fetch_assoc(mysql_query("SELECT * FROM `database` WHERE 1));
and to call it i use $user_info['column']
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();