SIMPLEST update to MYSQL from PHP - php

I am passing over a factory operations system to a new support team and I am writing a guide for that.
It has a VERY simple DB section tucked inside and I just want very basic set of procedures for demonstration to the team who are very IT literate but do not have any DB or PHP experience.
I have finished most of the guide but having a bit of a problem with a simple Quantity update procedure.
Be clear - I have no problem doing it but I have searched and searched for a simple answer and also everything I do seems just far more complex than it needs be. Can anyone assist with simplicity !
As the base exampler I am using the well tried
<?php
$con=mysqli_connect('localhost', 'bbbbbb', 'bbbbb', 'bbbbbbl') or die(mysql_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM orders_products");
echo "<table border='1'>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Quantity</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['products_id'] . "</td>";
echo "<td>" . $row['products_name'] . "</td>";
echo "<td>" . $row['products_quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
which gives a simple table at the level I need
NOW all I want to demonstrate is how to update some or all of the Product Quantities in the list back to the MYSQL database. BUT AS SIMPLY AS POSSIBLE Without using individual "Edits" for each row. Apologies if this is too low level for you chaps !

NOTE: Edited to improve secrurity, but this does NOT negate the need for prepared statements to prevent other SQL injection attacks.
Wrap
<form method='POST' action='?'> around the table.
Replace
echo "<td>" . $row['products_quantity'] . "</td>";
With
$iProctId = $row['products_id'];
$iQuantity = $row['products_quantity'];
echo "<td>";
echo "<input type='text' name='product[{$iProductId}]' value='{$iQuantity}'/>";
echo "</td>";
In your script:
foreach( $_POST['product'] as $iProductId => $iQuantity ) {
mysqli_query( $con,"
UPDATE
orders_products
SET
products_quantity = ".(int)$iQuantity."
WHERE
products_id = ".(int)$iProductId."
");
}
Disclaimer
This script is simple, but not safe! To get it safe: mysqli_real_escape_string and mysqli_prepare
Enjoy :)

Related

Why does my PHP code recognises NULL entities in my Oracle database as Unidentified Indexes?

I have a simple PHP coding which fetches data from a specific table within my Oracle database. It works fine in outputting the data from the tables on the PHP form but one thing I've noticed is my Error_Reporting function calls up several identical errors indicating there are unidentified indexes present in the table.
My Code:
<?php
include("ConnectionCode.php");
error_reporting(E_ALL);
$sql = 'SELECT * FROM ROVER';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
echo "<table border='1'>";
echo "<tr> <th>Rover ID</th> <th>Rover Name</th> <th>Launch_Date</th>
<th>Arrival_Date</th> <th>Manufacturer</th> </tr>";
while($row= oci_fetch_array($stid, OCI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row ['ROVER_ID'] . "</td>";
echo "<td>" . $row ['ROVER_NAME'] . "</td>";
echo "<td>" . $row ['LAUNCH_DATE'] . "</td>";
echo "<td>" . $row ['ARRIVAL_DATE'] . "</td>";
echo "<td>" . $row ['MANUFACTURER'] . "</td>";
echo "</tr>";
}
echo "</table>";
oci_free_statement($stid);
oci_close($conn);
?>
I made the logical assumption that these indexes were due to the NULL values present within some fields of the table. But my question is mainly this, is there anything I can do in the code to fix this? Or is it not really an issue?
The manual mentions:
mode: An optional second parameter can be any combination of the
following constants:
[...]
OCI_RETURN_NULLS: Creates elements for NULL fields. The
element values will be a PHP NULL.
I'm not very familiar with the OCI interface, but the implication here seems to be that yes, NULL fields are omitted by default, but you can return them by explicitly setting that flag:
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS))

Reference two SQL databases with a Join via PHP

I have written an SQL statement which works in phpmyadmin. I have two databases on the same server which I have used an INNERJOIN to connect them and im getting the correct results. I am building this up in php and so far have done a few normal queries and got the correct results. I have an include for my db, which is connecting to one database, now I want to connect to two and im not sure how I reference this in in my php sql statement. Can someone please help.
I have this.
<?php
error_reporting(0);
include './includes/opendb.php';
extract($_POST);
$sql1 = mysql_query("SELECT f_clients.CLIENT_COMPANY, vtmastertrail.consultant, f_clients.CLIENT_CODE, vtcards.description, vtmastertrail.inspdate_start, vtmastertrail.inspdate_end, vtcards.typeofcard, vtcards.colour, vtcards.frequency, vtcards.priorityon, vtmastertrail.islive, f_clients.CLIENT_DEFAULTINSPECTIONSELL
FROM `f_clients`
INNER JOIN tcards.vtcards ON tcards.vtcards.client_code = f_clients.CLIENT_CODE
INNER JOIN tcards.vtmastertrail ON tcards.vtmastertrail.card_id = tcards.vtcards.id
WHERE tcards.vtmastertrail.consultant = '".$con_name."'
AND tcards.vtmastertrail.inspdate_start >= '".$from_date."'
AND tcards.vtmastertrail.inspdate_start <= '".$to_date."'");
echo "<table border='1' align='center'>
<tr>
<th>Consultant</th>
<th>Client Code</th>
<th>Client</th>
<th>Address</th>
<th>Inspection Start Date</th>
<th>Inspection End Date</th>
<th>Type Of T-Card</th>
<th>T-Card Colour</th>
<th>Frequency</th>
<th>Priority</th>
<th>Report Sent Out</th>
<th>Cost</th>
</tr>";
while($row = mysql_fetch_array($sql1))
{
echo "<tr>";
echo "<td>" . $row['consultant'] . "</td>";
echo "<td>" . $row['client_code'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['inspdate_start'] . "</td>";
echo "<td>" . $row['inspdate_end'] . "</td>";
echo "<td>" . $row['typeofcard'] . "</td>";
echo "<td>" . $row['colour'] . "</td>";
echo "<td>" . $row['frequency'] . "</td>";
echo "<td>" . ($row['priorityon'] ? 'Yes' : 'No') . "</td>";
echo "<td>" . ($row['signedoff'] ? 'Yes' : 'No') . "</td>";
echo "<td>" . $row['CLIENT_DEFAULTINSPECTIONSELL'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
Im basically getting no results from this search.
here is my db file.
<?php
// ** database connection string
$conn = mysql_connect("localhost", "#####", "########") or die ('I cannot connect to the database because: ' . mysql_error());
// ** Tcards database
mysql_select_db ("tcards");
Ive changed hidden the credentials. I have another database called 'test' which is where the f_clients table is. This is on the same server and has the same login credentials. Can anyone help me out please?
You won't need to call mysql_select_db if you're planning to select from two separate databases.
Your query will need to use fully-qualified names (that means "test.f_clients.CLIENT_COMPANY", etc.). I think your ON clause will be OK as long as you fully qualify the DB names.
Note that MySQL functions (mysql_query, etc.) are deprecated; please consider switching to MySQLi or PDO. MySQLi is an easy switch.
Also pay attention to all Ian's comment above, about extracting the POST array and escaping data for your queries. You MUST code securely unless this is a company intranet behind a firewall someplace, and even then you cannot be assured it won't be exploited....
one thing you can do is add same user and password for both databases. or you can use view for overcome your problem. in practice i successful with adding same username and password to both databases. If you like try with "mysql workbench" that with easy to work with databases.

Once we create trigger in php page then do we need to create same in Mysql?

I am using Mysql for database purpose for my php code.
I have created trigger in php code as below, Now do I need to create it in mysql??
My following insert data into table, and also show content of tables. But action I performed in trigger does not make any change. Is there any problem in trigger?
Once it started working fine but after i changed table name it stopped working though I kept table name same my php page and mysql.
<html>
<body>
<?php
$id=$_POST['id'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$city=$_POST['city'];
$con=mysqli_connect('127.0.0.1:3306' ,'root','root','my_db');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="select * from student";
$result = mysqli_query($con,$sql1);
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
**$sql3 = "CREATE TRIGGER MysqlTrigger AFTER INSERT ON student FOR EACH ROW BEGIN INSERT INTO details VALUES ($id,$fname,$lname,$city);";**
mysqli_query($con,$sql3);
$sql5="INSERT INTO student (id,fname, lname, city)
VALUES
('$_POST[id]','$_POST[fname]','$_POST[lname]','$_POST[city]')";
mysqli_query($con,$sql5);
echo "1 record added";
print "<h2>After performing Trigger updated table details</h2>";
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
</tr>";
$sql4="select * from details";
$res = mysqli_query($con,$sql4);
while($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Short answer - no, you don't have to because creating it in the code also creates it in MySQL. But you have bigger problems.
Longer answer -
Triggers are part of the database, and typically you wouldn't create a trigger from code. You would create triggers the same way you create tables - create them once in MySQL and they stick around until you drop them.
Technically the code you have will work, but the CREATE TRIGGER statement will only succeed the first time it is called. In subsequent executions of that script the CREATE TRIGGER will error out because the trigger already exists. But since you aren't checking for errors, your script will probably continue on happily.
Also, the way your trigger is made, it will always insert the same record into the details table that was inserted when the trigger was created.
Finally, you have some serious security issues with your code:
You are directly using POST variables in SQL which opens you up to SQL Injection
Whatever user your site is running as probably shouldn't have permissions to execute DDL statements like CREATE TRIGGER

Can you store selected sql query values in the url and then retrive them with $_GET?

I'm trying to make it so that when a users clicks one of the rows,it will take them to a new page whose link is given as the value of the row they selected and then retrieve the value with $_GET["timesub"].
Anyone know how to do this?
mysql_select_db("RRRC", $con);
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum=$loc");
echo "<table border='1'>
<tr>
<th> Submitted </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";
Assuming that $row['timesub'] identifies a row in your data set (I doubt it), just fix your echo instruction as:
echo "<td>" . $row['timesub'] . "</td>";
Escaping the html quotes properly.
echo "<td><a href='roomdata.php?timestamp=".$row['timesub']."'>".$row['timesub']."</a></td>";
Close the outer " before the . concatenator, replace the inner " with '
A good practice is to use the row's primary key to reference your get query; but yes - this can be done.
All you have to do is store the get data into a sanitized variable, and perform the required SQL lookup / data display.
EX:
$roomnum=mysql_real_escape_string(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['roomnum']));
Now, given that "roomnum" is your primary key just look it up and display:
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum='$roomnum'");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";

Trying to pass a student key from a html form to a php file to scan a database

Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

Categories