how do I write mysql_fetch_array code in codeigniter
<?php
$result = mysql_query("select * from tb_mhs");
$jsArray = "var dtMhs = new Array();\n";
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['nim'] . '">' . $row['nim'] . '</option>';
$jsArray .= "dtMhs['" . $row['nim'] . "'] = {nama:'" . addslashes($row['nama']) .
"',jrsn:'".addslashes($row['jurusan'])."'};\n";
}
?>
Form Input :
<td><input type="text" name="nm" id="nm"/></td>
<td><input type="text" name="jrsn" id="jrsn"/></td>
Javascript :
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(nim) {
document.getElementById('nm').value = dtMhs[nim].nama;
document.getElementById('jrsn').value = dtMhs[nim].jrsn;
};
</script>
If you want to return result as a array from the database, you can use something like this
// in application/config/autoload.php, make database available globally
$autoload['libraries'] = array('database');
// fetch the results from the database
$query = $this->db->get('tb_mhs'); // produces select * from tb_mhs
// get the result as a array
$result = $query->result_array();
// to do the other operations you were doing you can use a loop
foreach ($result as $key => $item) {
// do stuff
}
Related
I would like to pass a PHP array from JavaScript.
PHP Data Table
---------------------------
| adminID | adminEmail |
===========================
| 1 | abc#gmail.com |
| 2 | xyz#ymail.com |
===========================
Javascript
<script>
function checkuser_callback_function($el, value, callback) {
var $array = new Array("xyz#gmail.com","abc#ymail.com");
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
I want to pass that adminEmail here var $array = new Array("..","..");
I have tried alot in php but I didn't get any result.
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
$array = $row;
$str = "'" . implode ( "', '" ,$array ) . "'";
$parts = split("'", $str);
print_r($str);
}
?>
You can use php to create javascript array. Then use the same in the script later. Please note that , just to differentiate, I have called javascript array jArray instead of $array. Rest is explained along in the script only. Hope this helps..
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
//start script tag
echo "<script>\n";
// javascript array decalaration beginning
echo "var jArray = new Array(";
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
echo $arrStr;
// end javascript array
echo ");\n";
echo "</script>\n";
?>
<?php
include 'ePHP/config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
?>
<script>
function checkuser_callback_function($el, value, callback) {
var $array = Array(<?php echo $arrStr; ?>);
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
I need to submit a dynamically created field set via ajax call to a php to insert the data to DB. The list is for product items for a specific supplier. I need to make a ajax call , but dont know how to submit the named arrays in data field.
My HTML:
<div class='col-md-2 '><input name="item_number[]" id="item_number" class="form-control" placeholder='item number' /></div>
<div class='col-md-4 '><input name="description[]" id="description" class="form-control" placeholder='description' /></div>
<div class='col-md-1 '><input name="quantity[]" id="quantity" class="form-control" placeholder='Quantity' /></div>
<div class='col-md-2 '><input name="unit_price[]" id="unit_price" class="form-control" placeholder='Unit Price' /></div>
<div class='col-md-2 '><input name="sales_price[]" id="sales_price" class="form-control" placeholder='Sales Price' /></div>
<div><button name="add_item" id="add_item" class="btn btn-primary">+</button></div>
How can i get the value set posted to my PHP file and then insert them via a for loop
My PHP file is as below:
$supplier_selection = $_POST['supplier_id'];
$item_id = $_POST['item_id'];
$array_description = $_POST['description'];
$array_quantity = $_POST['quantity'];
$array_unit_price = $_POST['unit_price'];
$array_sale_price = $_POST['sale_price'];
foreach ($item_id as $key => $value) {
$check_item_id = "SELECT item_id from products where item_id='" . $mysqli->real_escape_string($item_id [$key]) . "'LIMIT 1";
$resultset = $mysqli->query($check_item_id);
if ($resultset->num_rows == 0) {
//perform insert to table
$insert_product = "INSERT INTO `products` (`id`, `item_id`, `supplier_id`, `description`, `quantity`, `purchase_price`, `retail_price`) "
. "VALUES (NULL, '" . $mysqli->real_escape_string(item_id) . "','$supplier_selection', '" . $mysqli->real_escape_string($array_description[$key]) . "', '" . $mysqli->real_escape_string($array_quantity[$key]) . "', '" . $mysqli->real_escape_string($array_unit_price[$key]) . "', '" . $mysqli->real_escape_string($array_sale_price[$key]) . "')";
$insert_item = $mysqli->query($insert_product);
if (!$insert_item) {
echo $mysqli->error;
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
} else {
echo "successfully inserted" . $mysqli->real_escape_string($item_id[$key]) . "";
echo "<script>";
echo "alert('Items Added successfully')";
echo "</script>";
}
}
}
I think you use jQuery and $.ajax so you can just serialize the form you need and it will gather all data from the form in proper format:
$('#form_id').serialize()
You can insert it into the data param into $.ajax call
$.ajax({
url: '/your/url/here',
data: $('#form_id').serialize()
});
In the php code it is very stupid to make DB queries in the loop.
I see you are getting data from the HTML form by POST request so there will not be millions of items to loops through.
Here is the more efficient code you may use, kinda 2 times less amoutn of DB queries:
<?php
$supplier_selection = $_POST[ 'supplier_id' ];
$item_id = $_POST[ 'item_id' ];
$array_description = $_POST[ 'description' ];
$array_quantity = $_POST[ 'quantity' ];
$array_unit_price = $_POST[ 'unit_price' ];
$array_sale_price = $_POST[ 'sale_price' ];
//get all item IDs received
$all_keys = array_keys( $item_id );
//get all items in DB with item_id in received array
$not_to_insert_sql = "SELECT item_id from products where item_id IN (" . implode( ',', $all_keys ) . ")";
$not_to_insert = $mysqli->query( $not_to_insert_sql );
//need to get only IDs
for ( $i = 0, $c = count( $not_to_insert ); $i < $c; ++$i ) {
$not_to_insert[] = $not_to_insert[ $i ][ 'item_id' ];
}
//let's get difference between what's in the array and what is already in DB
$to_insert = array_diff( $all_keys, $not_to_insert );
// let's loop only what we need to insert
for ( $i = 0, $c = count( $to_insert ); $i < $c; ++$i ) {
//perform insert to table
$insert_product = "INSERT INTO `products` (`id`, `item_id`, `supplier_id`, `description`, `quantity`, `purchase_price`, `retail_price`) "
. "VALUES (NULL, '" . $mysqli->real_escape_string( item_id ) . "','$supplier_selection', '" . $mysqli->real_escape_string( $array_description[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_quantity[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_unit_price[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_sale_price[ $key ] ) . "')";
$insert_item = $mysqli->query( $insert_product );
if ( ! $insert_item ) {
echo $mysqli->error;
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
}
else {
echo "successfully inserted" . $mysqli->real_escape_string( $item_id[ $key ] ) . "";
echo "<script>";
echo "alert('Items Added successfully')";
echo "</script>";
}
}
Okay, so I'm working on a PHP site, I have descriptions of the product under the image, what I'm need to do is limit the amount of characters on the page and add a click here or.. For the viewers to be directed to that products page to see the full description. FYI very new to PHP, here is what I have so far. So question is do I use PHP or javascript or both and how do I do that ?
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo $product_name . "</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo "<a href='deleteproduct.php'><button>delete</button></a>";
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
using strlen and substr we can achieve this
$length = 150
$x = 'string';
if(strlen($x)<=$length)
{
echo $x;
}
else
{
$y=substr($x,0,$length) . '...';
echo $y;
}
In php, i have used an sql query to fetch the data like :-
$sql="Select * from xyz";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
}
Now i want to use all the values attained using $row["id"] in javascipt function and use it in a variable (var j , lets say). How to do this?
Try something like this:
<?php
$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$errorData[]=$row["id"]
}
$errorJson = json_encode($errorsData);
?>
<script>
var errorJson = <?= $errorJson ?> ;
console.log(errorJson);
<script>
Good luck!!
in jquery I would have done like this,
php
$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$arr_json[] = $row['id'];
}
echo json_encode($arr_json);
jquery
$.get(
<THAT CALLED URL>,
function(ret_data){
console.log(ret_data);
/* you can use the ret_data as ret_data.<INDEX> */
}
);
Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>