Value == DisplayText in Field Options or else Fields are Blank - php

I've already posed this question on the jquery-jtable Github issues section here: https://github.com/hikalkan/jtable/issues/703 . There doesn't seem to be much knowledge being shared there at this time and this issue is significantly hamstringing further development of my project.
I am practically certain I am missing something relatively simple because based on the documentation here: http://www.jtable.org/ApiReference#fopt-options this really should be straightforward with no issues.
Note, this simplified version of code should demonstrate the issue and is not representative of exactly how the code is being implemented. that is, I am strictly trying to solve the reproducible issue not how best to use it in my much larger project.Here's a copy paste of the issue:
Let's make the SQL table:
--Create "employee titles" table
create table employee_titles (employeetitleid int not null IDENTITY, employeetitle varchar(50) not null,
constraint PK_employee_titles_employeetitleid
primary key clustered (employeetitleid))
go
Now let's make the jtable:
<html>
<head>
<link href="/jtabphp/themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="/jtabphp/scripts/jtable/themes/lightcolor/blue/jtable.css" rel="stylesheet" type="text/css" />
<script src="/jtabphp/scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/jtabphp/scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="/jtabphp/scripts/jtable/jquery2.3.0.jtable.js" type="text/javascript"></script>
</head>
<body>
<div id="EmployeeTitles" style="width: 600px;"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#EmployeeTitles').jtable({
title: 'Employee Titles',
actions: {
listAction: 'PersonActions.php?action=list',
},
fields: {
employeetitleid: {
key: true,
create: false,
edit: false,
title: 'Title ID',
width: '10%'
},
employeetitle: {
title: 'Employee Title',
options: 'DropdownSelectors.php?Selector=employeetitle',
optionsSorting: 'text',
width: '45%'
}
}
});
//Load person list from server
$('#EmployeeTitles').jtable('load');
});
</script>
</body>
</html>
Let's create the personactions.php file which runs the SQL queries for action==list:
<?php
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
try {
//Getting records (listAction)
if($_GET["action"] == "list")
{
//Get records from database
$sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles";
$stmt = $conn->query($sql_select);
//Add all records to an array
$rows = $stmt->fetchall(PDO::FETCH_ASSOC);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
else if($_GET["action"] == "create")
{
//Insert record into database
$sql_insert = "INSERT INTO employee_titles (employeetitle) VALUES (?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bindValue(1, $_POST['employeetitle']);
$stmt->execute();
//Get last inserted record (to return to jTable)
$sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles WHERE employeetitleid = ##IDENTITY";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Updating a record (updateAction)
else if($_GET["action"] == "update")
{
//Update record in database
$sql_update = "UPDATE employee_titles SET employeetitle = ? WHERE employeetitleid = ?;";
$stmt = $conn->prepare($sql_update);
$stmt->bindValue(1, $_POST['employeetitle']);
$stmt->bindValue(2, $_POST['employeetitleid']);
$stmt->execute();
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Deleting a record (deleteAction)
else if($_GET["action"] == "delete")
{
//Delete from database
$sql_delete = "DELETE FROM employee_titles WHERE employeetitleid = ?;";
$stmt = $conn->prepare($sql_delete);
$stmt->bindValue(1, $_POST['employeetitleid']);
$stmt->execute();
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Close database connection
$conn = null;
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}
?>
Finally, let's make the DropdownSelectors.php file that is going to query our dropdown contents. depending on how I construct this file I will get 2 different results with neither being satisfactory.
In this 1st example I am going to make [DisplayText] == [Value]. This will correctly display the employee title information in the jtable view and correctly populate the dropdown for create/edit. However, the [Value] reported by the dropdown is not nearly as useful for later queries as it would be if it were actually the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example.
Example DropdownSelectors.php #1:
<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitle [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
?>
In this 2nd example I am going to make [DisplayText] and [Value] pull from different columns in the employee_titles table. This will cause the employee title column of the jtable to be blank but still correctly populate the dropdown for create/edit. In this case, the [Value] reported by the dropdown is very useful for later queries as it actually reports the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example. It is completely unacceptable that the displayed jtable column appear blank, however.
Example DropdownSelectors.php #2:
<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
?>
Now that you have all of the code necessary to completely reproduce this very reproducible issue can anyone tell me how to fix it so htat the listed fields display the DisplayText and the dropdown options issue the vlaue that equates to an ID #? I am beginning to believe there is a display bug in jtable itself and that a small fix somewhere would cause the information to appear in the jtable view.
See the linked github issue for some of the workarounds I have attempted and why they do not work.

Okay! I solved this one. Holy cow do I feel dumb. I had a faulty understanding of how Value relates to the record and field name. I had assumed Value was strictly the information passed when a dropdown selection was made. However, as I see now, Value also corresponds to the the record that is contained in the jtable field. Thus, the fieldname will have to correspond to the column name the data comes under just like a standard jtable field does. Value must correspond to that column. So, to fix the provided example we do the following:
if ($_GET['Selector'] == "employeetitleid") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
and
employeetitleid: {
title: 'Employee Title',
dependsOn: 'anotherfield',
options: function (data) { if (data.source == 'list') { return 'DropdownSelectors.php?Selector=employeetitleid&filter=>0'; }
return './../DropdownSelectors.php?Selector=employeetitleid&filter==' + data.dependedValues.anotherfield },
optionsSorting: 'text',
width: '45%'
}
The above example also includes the logic to operate the DepndsOn feature for cascaded dropdowns which is how I ran into this issue to begin with (having [Value]==[DisplayText] "worked well until then). In this example the jtable will show a column name of "Employee title" and the fields will show the text strings that correlate to the title id number. However the actual data being worked with is the title id number which, not surprisingly, makes all of the queries and the field configurations must easier and more efficient.

Related

Move MySQL table row to another table using PDO

i tried to follow this mysql - move rows from one table to another with action to perform a "move to archive" function using PDO and i am failing miserably.
So i have created a job card system, and to cut it short, when a job is complete, i have a "ARCHIVE" button that essentially needs to move the selected job card from table "repairs" into table "archived_repairs". The 2 tables are exactly the same, it just needs to be deleted from repairs table and moved to archived_repairs table in case we need to come back to it at a later stage.
This is the button/link i am using on my CRUD table:
<td>Archive</td>
The above is fine and dandy and goes to a page i named "archive_repair.php" with the following php code:
<?php
require_once "connection.php";
if (isset($_REQUEST['archive_id']))
{
try
{
$job_number = $_REQUEST['archive_id'];
$select_stmt = $db->prepare('SELECT * FROM repairs WHERE job_number =:job_number');
$select_stmt->bindParam(':job_number', $job_number);
$select_stmt->execute();
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
catch(PDOException $e)
{
$e->getMessage();
}
}
if (isset($_REQUEST['btn_archive']))
{
$job_number = $_REQUEST['job_number'];
$date = $_REQUEST['date'];
$client_full_name = $_REQUEST['client_full_name'];
$client_email = $_REQUEST['client_email'];
$client_phone = $_REQUEST['client_phone'];
$item_for_repair = $_REQUEST['item_for_repair'];
$repair_description = $_REQUEST['repair_description'];
$hardware_details = $_REQUEST['hardware_details'];
$diagnostic_fee = $_REQUEST['diagnostic_fee'];
$tech_assigned = $_REQUEST['tech_assigned'];
$current_status = $_REQUEST['current_status'];
$technician_notes = $_REQUEST['technician_notes'];
$admin_notes = $_REQUEST['admin_notes'];
$invoice_status = $_REQUEST['invoice_status'];
$invoice_number = $_REQUEST['invoice_number'];
if (empty($invoice_status))
{
$errorMsg = "Please change Invoice Status Before Archiving this Job Card";
}
else if (empty($invoice_number))
{
$errorMsg = "Please Enter a SAGE Invoice Reference Before Archiving this Job Card";
}
else
{
try
{
if (!isset($errorMsg))
{
$archive_stmt = $db->prepare('INSERT INTO archived_repairs job_number=:job_number, date=:date, client_full_name=:client_full_name, client_email=:client_email, client_phone=:client_phone, item_for_repair=:item_for_repair, repair_description=:repair_description, hardware_details=:hardware_details, diagnostic_fee=:diagnostic_fee, tech_assigned=:tech_assigned, current_status=:current_status, technician_notes=:technician_notes, admin_notes=:admin_notes, invoice_status=:invoice_status, invoice_number=:invoice_number');
$archive_stmt->bindParam(':job_number', $job_number);
$archive_stmt->bindParam(':date', $date);
$archive_stmt->bindParam(':client_full_name', $client_full_name);
$archive_stmt->bindParam(':client_email', $client_email);
$archive_stmt->bindParam(':client_phone', $client_phone);
$archive_stmt->bindParam(':item_for_repair', $item_for_repair);
$archive_stmt->bindParam(':repair_description', $repair_description);
$archive_stmt->bindParam(':hardware_details', $hardware_details);
$archive_stmt->bindParam(':diagnostic_fee', $diagnostic_fee);
$archive_stmt->bindParam(':tech_assigned', $tech_assigned);
$archive_stmt->bindParam(':current_status', $current_status);
$archive_stmt->bindParam(':technician_notes', $technician_notes);
$archive_stmt->bindParam(':admin_notes', $admin_notes);
$archive_stmt->bindParam(':invoice_status', $invoice_status);
$archive_stmt->bindParam(':invoice_number', $invoice_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
This is my connection.php file:
<?php
$db_host="localhost"; //localhost server
$db_user="ecemscoz_ecemsapp"; //database username
$db_password="C3m3t3ry!#"; //database password
$db_name="ecemscoz_ecemsapp"; //database name
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
When i click on the ARCHIVE button/link, the page is just blank (white screen), no errors show, nothing is moved to the other database and nothing is deleted. Ive only been coding PHP since 2020 so still new at this, but from my understanding this should of worked... Am i missing something in my code that i am not seeing?
You'll have a much easier time doing this directly in MySQL.
Something like the following should be essentially all you need.
$archive_stmt = $db->prepare("INSERT INTO archived_repairs (
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
) (
SELECT
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
FROM
repairs
WHERE
job_number =:job_number )");
$archive_stmt->bindParam(':job_number', $job_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}

Want to fetch data from database based on dropdown list selection using php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}

PHP MySQL - Function

i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

Error adding order: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Hey guys I would love your help in regards to the code below, I am quite new to php and and sql, and I am trying to blind these values for a order check out process. There are multiple pages that I need to capture the information from....
I have looked over this code for hours and I am unable to find where I am going wrong...
This may be because I am really not sure where I need to be looking to fix this problem. Any help or advice would help so much!
function writeOrderToDatabase(){
// open database connection
include 'includes/connection.php';
// store order date in Australian format for printouts etc
$_SESSION['orderDate'] = date('d-m-Y');
try{
// create our sql insert orders statement
$sql = "INSERT INTO orders SET orderNbr=: orderNbr,custNbr=:custNbr,orderDate=:orderDate, OrderNetValue=:OrderNetValue,deliverTo = :deliverTo,
deliveryAddress1 = :deliveryAddress1, deliveryAddress2 = :deliveryAddress2, deliverySuburb = :deliverySuburb,
deliveryState = :deliveryState, deliveryPostCode = :deliveryPostCode, deliverySuburb = :deliverySuburb, deliveryState = :state, deliveryPostCode = :deliveryPostCode, deliveryInstructions = :deliveryInstructions, shippingValue=:shippingValue,
paymentType=:paymentType, paymentRef=:paymentRef;";
// prepare the statement
$statement = $pdo->prepare($sql);
$orderNbr = 0;
// bind the values
$statement->bindValue(':orderDate', date('Y-m-d'));
$statement->bindValue(':custNbr', $_SESSION['custNbr']);
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':OrderNetValue', $_SESSION['OrderNetValue']);
$statement->bindValue(':deliverTo', $_SESSION['deliverTo']);
$statement->bindValue(':deliveryAddress1', $_SESSION['deliveryAddress1']);
$statement->bindValue(':deliveryAddress2', $_SESSION['deliveryAddress2']);
$statement->bindValue(':deliverySuburb', $_SESSION['deliverySuburb']);
$statement->bindValue(':deliveryState', $_SESSION['deliveryState']);
$statement->bindValue(':deliveryPostCode', $_SESSION['deliveryPostCode']);
$statement->bindValue(':deliveryInstructions', $_SESSION['deliveryInstructions']);
$statement->bindValue(':shippingValue', $_SESSION['shippingValue']);
$statement->bindValue(':paymentType', $_SESSION['paymentType']);
$statement->bindValue(':paymentRef', $_SESSION['paymentRef']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
// execute the statement
$success = $statement->execute();
} // end try
catch (PDOException $e) {
echo 'Error adding order: ' . $e->getMessage();
exit();
} // end catch
// test the result and get order nbr just created or display appropriate message
if ($success) {
echo $sql = 'SELECT orderNbr FROM orders ORDER BY orderNbr';
foreach ($conn->query($sql) as $row) {
print $row['orderNbr'] . "\t";
}
}
else {
die("<p>Unable to retreive Order Nbr </p>");
}
// read cart and insert orderedItem record(s) and update stock on hand in product records
foreach($_SESSION['cart'] as $prodNbr => $value) {
// store required details in variables
$qtyOrdered = $_SESSION['cart'][$prodNbr]['qtyOrdered'];
$qtyOnHand = $_SESSION['cart'][$prodNbr]['qtyOnHand'];
$sellingPrice = $_SESSION['cart'][$prodNbr]['price'];
try {
// create orderedItem table sql insert statement
$sql = "INSERT INTO orderedItem SET orderNbr=:custNbr,prodNbr=: prodNbr, qtyOrdered=:qtyOrdered,sellingPrice = :sellingPrice;";
} // end try
catch (PDOException $e) {
echo 'Error adding orderedItem: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the orderedItem table insert</p>");
}
// create new quantity on hand value for the product record
$newQtyOnHand = $qtyOnHand - $qtyOrdered;
try {
// create product table sql update statement
$sql="UPDATE product SET prodNbr= :prodNbr,prodName= :prodName,price= :price,qtyOnHand= :qtyOnHand,description= :description, photo= :photo,thumbNail= :thumbNail ,suppCode= :suppCode ;";
} // end try
catch (PDOException $e) {
echo 'Error updating product qtyOnHand: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the product table update</p>");
}
} // end of foreach
} // end of function
Here:
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
These bind don't exist in the query.
Besides,
orderNbr=: orderNbr
should be
orderNbr = :orderNbr
Please note you don't bind it either.
Also, you're having twice the following parameters in the query:
deliveryState = :state
deliveryState = :deliveryState
deliveryPostCode = :deliveryPostCode
deliveryPostCode = :deliveryPostCode
You have a bad placeholder token first off: orderNbr=: orderNbr needs to be orderNbr=:orderNbr; Note the whitspace. Secondly, even if that was correct i dont see you binding :orderNbr anywhere.
I would think though that the order number should be an autoincrement integer field, and if that is the case you should not include it in your insert.

Categories