Change code from mysql to mssql in a php file - php

I'm new to php and sql.
The codes below are written in php and working fine when connecting to a mysql database. SELECT query is working and UPDATE query is working.
But when connecting to an mssql database, the codes don't work well.
I need to convert them to connect to a similar mssql database.
Thank you.
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Designation</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<?php
$sql_query = "SELECT id, firstname, lastname, address, email FROM
myguests LIMIT 10";
$resultset = mysqli_query($conn, $sql_query) or die("database
error:". mysqli_error($conn));
while( $developer = mysqli_fetch_assoc($resultset) ) {
?>
<tr id="<?php echo $developer ['id']; ?>">
<td><?php echo $developer ['id']; ?></td>
<td><?php echo $developer ['firstname']; ?></td>
<td><?php echo $developer ['lastname']; ?></td>
<td><?php echo $developer ['address']; ?></td>
<td><?php echo $developer ['email']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
/* Database connection start */
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$conn = mysqli_connect($servername, $username, $password, $dbname) or
die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<?php
include_once("db_connect.php");
$input = filter_input_array(INPUT_POST);
if ($input['action'] == 'edit') {
$update_field='';
if(isset($input['firstname'])) {
$update_field.= "firstname='".$input['firstname']."'";
} else if(isset($input['lastname'])) {
$update_field.= "lastname='".$input['lastname']."'";
} else if(isset($input['address'])) {
$update_field.= "address='".$input['address']."'";
} else if(isset($input['email'])) {
$update_field.= "email='".$input['email']."'";
}
if($update_field && $input['id']) {
$sql_query = "UPDATE myguests SET $update_field WHERE id='" .
$input['id'] . "'";
mysqli_query($conn, $sql_query) or die("database error:".
mysqli_error($conn));
}
}

The rough equivalent of MySQL LIMIT in SQL Server is TOP, so you may try something like:
SELECT TOP 10 id, firstname, lastname, address, email
FROM myguests
ORDER BY <some_column>;
Note carefully that I added an ORDER BY clause to your query. Using LIMIT (or TOP) without ORDER BY is fairly meaningless, because you haven't told SQL which 10 rows you want, relative to some ordering.

Related

how to add values for each colum for each day?

I have a Table which Input all the necessary data to do statistics. i now face the issue that i dont know how to add up the values for each colum but that it only adds the values up for each day. and then Displays it in a row or another Table.
this Code is what i use to call out all of the values and insert them into a table
<html>
<head>
<title>Your Home Page</title>
</head><body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM table ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error());
$datum = '';
while($set = mysqli_fetch_assoc($result)) {
?>
<tr>
<td>
<?php
if ($datum == $set["Date"]) {
echo ' ';
} else {
echo $set["Date"];
}
?>
</td>
<td><?php echo $set["ParticipantID"]; ?></td>
<td><?php echo $set["Gender"]; ?></td>
<td><?php echo $set["Hand"]; ?></td>
<td><?php echo $set["Under18"]; ?></td>
<td><?php echo $set["Adult"]; ?></td>
<td><?php echo $set["r"]; ?></td>
<td><?php echo $set["c"]; ?></td>
<td><?php echo $set["l"]; ?></td>
<td><?php echo $set["Cash"]; ?></td>
<td><?php echo $set["Card"]; ?></td>
<td><?php echo $set["Ammount"]; ?></td>
</tr>
<?php $datum = $set["Date"]; ?>
<?php
}
?>
</table> </body></html>
So for 04-01-2018 for the colum R the total summed up value should be 2. etc.
Thanks for the help.
Kind Regards
Mark
The first way of solving this problem is to use the second MySQL query to get total values for each date. After that create a function printDateTableRow to print each row of the table. Using the mysqli_fetch_assoc($totalMysqliResult) parameter of this function, you can pass values of a row with total values for each new date.
Another way is to use the the WITH ROLLUP group modifier (you can try to write such query by yourself).
Here is the working code for the first way:
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM `table` ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
$totalMysqliResult = mysqli_query($mysqli, '
SELECT
Date, "" AS ParticipantID, "" AS Gender, "" AS Hand,
SUM(Under18) AS date_total_Under18,
SUM(Adult) AS date_total_Adult, SUM(r) AS date_total_r,
SUM(c) AS date_total_с, SUM(l) AS date_total_l,
SUM(Cash) AS date_total_Cash, SUM(Card) AS date_total_Card,
SUM(Amount) AS date_total_Amount
FROM `table`
GROUP BY Date
ORDER BY Date ASC') or die(mysqli_error($mysqli));
/**
* #param $row
* #param null $dateFieldHeader
*/
function printDateTableRow($row, $dateFieldHeader = null) {
?><tr><?
foreach ($row as $key => $curVal) {
?><td><?
if ($key == 'Date') {
echo $dateFieldHeader == null ? $curVal : $dateFieldHeader;
} else {
echo $curVal;
}
?></td><?
}
?></tr><?
}
$previousDate = null;
$oneDateRowsCount = 0;
while($row = mysqli_fetch_assoc($result)) {
if ($row['Date'] == $previousDate) {
$oneDateRowsCount++;
printDateTableRow($row, ' ');
} else {
if ($previousDate !== null) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
printDateTableRow($row);
$oneDateRowsCount = 1;
}
$previousDate = $row['Date'];
}
// add total for the last rows with the same date
if ($oneDateRowsCount > 1) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
?>
</body>
</html>
You should refactor this code in OOP style and use PDO instead of mysqli.

QUERY works in phpyMyAdmin but not in PHP

My Query don't work in PHP but when I test it in my database it works well.
Code:
<?php
//Database connectie
$link = mysqli_connect("*", "*", "*", "*") or die("Error ". mysqli_error($link));
ini_set('memory_limit', '1024M'); // or you could use 1G
//Query //
$query = "SET SQL_BIG_SELECTS = 1;";
$query = "SELECT * FROM datakram, datakram2, datakram3, datakram4 WHERE datakram.ISIN = datakram2.ISIN AND datakram2.ISIN = datakram3.ISIN AND datakram3.ISIN = datakram4.ISIN";
$result = mysqli_query($link, $query);
?>
<table>
<thead>
<tr class="warning">
<th>Naam</th>
<th>ISIN</th>
<th>Jaar</th>
<th>Closely Held Shares</th>
<th>Outstanding Sahres</th>
<th>Market capitalistion</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $row['company-name'];?></td>
<td><?php echo $row['ISIN'];?></td>
<td>2017</td>
<td><?php echo $row['2017'];?></td>
<td><?php echo $row['2017-shares'];?></td>
<td><?php echo $row['2017-market'];?></td>
</tr>
<?php
}
?>
Knows somebody why? I have tried: $result = mysqli_multi_query($link, $query); But that didn't work.
I have fix it, don't tell me how ;) but it works. Here if somebody need it:
//Database connectie
$link = mysqli_connect("*", "*", "*", "*") or die("Error ". mysqli_error($link));
ini_set('memory_limit', '1024M'); // or you could use 1G
//Query //
$query = "SET SQL_BIG_SELECTS = 1;";
$query .= "SELECT * FROM datakram, datakram2, datakram3, datakram4 WHERE datakram.ISIN = datakram2.ISIN AND datakram2.ISIN = datakram3.ISIN AND datakram3.ISIN = datakram4.ISIN";
if (mysqli_multi_query($link, $query)) {
do {
?>
<table>
<thead>
<tr class="warning">
<th>Naam</th>
<th>ISIN</th>
<th>Jaar</th>
<th>Closely Held Shares</th>
<th>Outstanding Sahres</th>
<th>Market capitalistion</th>
</tr>
</thead>
<tbody>
<?php
if ($result = mysqli_store_result($link)) {
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $row['company-name'];?></td>
<td><?php echo $row['ISIN'];?></td>
<td>2017</td>
<td><?php echo $row['2017'];?></td>
<td><?php echo $row['2017-shares'];?></td>
<td><?php echo $row['2017-market'];?></td>
</tr>
<?php
}
}
} while (mysqli_next_result($link));
}
?>

Update MySQL database using HTML/PHP table (inline)

I'm trying to update my database using the html/php table with save button to confirm the changes and save in database.
Here's my Table
How can I edit the 'Quantity' row like text field and save with the button to confirm.
this is my table
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td>
</tr>";
}
?>
</tbody>
</table>
Please help. Thanks!
Put your table inside a form.
<form action="give_your_action_page" method="post">
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td><input type='number name='".$row[1]."' value='".$row[3]."'/></td>
</tr>";
}
?>
</tbody>
</table>
Now at your action page you can access the form values using $_POST array using the value in "Description" field.
For eg : $_POST["banana"] will give the quantity of banana.
Update the database using these values.
You're going to change a field that is not in the database?
because
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td> ----------------> ? (empty) ?
</tr>
You must first create a field called Quantityin your database, then try again if it was a difficult ask questions.
Ok your Code is a really bad , well most of it , and your Q was really hard to understand , but its ok , try to be more accurate next time =) , this answer that i came with is depends on my understanding to what you tried to ask .
I suggest that you topic from w3shool : Select data from database
In my answer or in my Code if we can say that , I used PDO , Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Search for it on Google and read some info about how it works and try to learn it , its simple and its the same as ( MYSQLI ) .
This is my Code which i tested it many times and it works , this code can be written in many ways but i tried to make it as simple as i can .
<?php
// Start of the first part ( connect to the database usnig PDO
$servername = "localhost";
$username = "root";
$password = "";
$database = "your database name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// END of the first part
// second part : bring the new quantity from the field
if(isset($_POST['update']))
{
$newquantity = $_POST['newQu'];
$itemName = $_POST['item'];
$UpdateOnQuantity = $conn->prepare( "UPDATE hr SET Quantity = ? WHERE Item = ?");
$UpdateOnQuantity->execute(array($newquantity,$itemName));
if($UpdateOnQuantity)
{
}
else
{
echo "error";
}
}
$FetchNewQuantity = $conn->prepare("SELECT * FROM hr");
$FetchNewQuantity->execute();
?>
<html>
<head>
</head>
<body>
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<?php
while($FetchedData = $FetchNewQuantity->FETCH(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $FetchedData['Item']; ?></td>
<td><?php echo $FetchedData['Description']; ?></td>
<td><?php echo $FetchedData['Unit']; ?><td>
<td><?php echo $FetchedData['Quantity']; ?></td>
<td>
<form action="test2.php" method="POST">
<input type="hidden" name="item" value="<?php echo $FetchedData['Item']; ?>">
<input type="text" name="newQu">
<input type="submit" name="update">
</form>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
This is my code hope it help you , i tested many times as i said so if it did not work with you let me know , and if you did not like PDO just replace PDO code with the normal Mysqli code .
Edit : i edited the code again , did not noticed that you linked your table . i added a while loop so it can show all the data in your table .

Script for deleting table rows not working in MySQL & PHP

I want to delete a table row from my database with MySQL and PHP. I have searched through my code and I can't figure out what I'm doing wrong. I think I am close to getting it, probably something simple that I'm not realizing.
If I hover over the delete link there is a link showing with the correct ID number of the row to delete. But if I click it, it isn't working. It just refreshes the screen.
This is my code for index.php:
<!-- Table -->
<form action="index.php" method="get" id="dispatch">
<div class="col-md-8 column">
<fieldset>
<legend>Incident Board (Incidents in red are active)</legend>
<div class="scroll-bar">
<table>
<thead>
<tr>
<th>Incident #</th>
<th>Town</th>
<th>Location</th>
<th>Incident Type</th>
<th>Time/Date</th>
<th>Admin</th>
<th>Delete Entry</th>
</tr>
</thead>
<tbody>
<?php
if( isset($_POST['town']) )
{
$town = $_POST['town'];
}
if( isset($_POST['location']) )
{
$location = $_POST['location'];
}
if( isset($_POST['incident_type']) )
{
$incident_type= $_POST['incident_type'];
}
if( isset($_POST['time_date']) )
{
$time_date= $_POST['time_date'];
}
if( isset($_POST['admin']) )
{
$admin = $_POST['admin'];
}
if( isset($_POST['id']) )
{
$id = $_POST['id'];
}
$db = mysqli_connect('localhost','root','') or die("Database error");
mysqli_select_db($db, 'cad');
$result= mysqli_query($db, "SELECT * FROM `cad` ORDER BY `time_date` DESC LIMIT 20");
while($row = mysqli_fetch_array($result))
{
$town = $row['town'];
$location = $row['location'];
$incident_type = $row['incident_type'];
$time_date = $row['time_date'];
$admin = $row['admin'];
$id = $row['id'];
echo "
<tr>
<td class=\"id-center\">
".$id."
</td>
<td >
".$town."
</td>
<td>
".$location."
</td>
<td >
".$incident_type."
</td>
<td >
".$time_date."
</td>
<td >
".$admin."
</td>
<td>
<span class=\"glyphicon glyphicon-trash\"></span>
</td>
</tr>";
}
mysqli_close($db);
?>
</tbody>
</table>
</div>
</fieldset>
</div>
</form>
<!-- End -->
This is my delete.php code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("cad", $dbhandle);
mysql_query("DELETE FROM cad WHERE id = ".$_GET['id']."");
header('location: index.php');
?>
mysql is deprecated, instead of this use mysqli
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$con=mysqli_connect($hostname, $username, $password,"cad");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"DELETE FROM cad WHERE id = ".$_GET['id']."");
mysqli_close($con);
?>

how to store the printed value in mysql table using php

I am printing values in the address bar using the get variable,it works perfectly, then my problem is i want store the printed values into a mysql table, but it only stores null values, please help me where i am going wrong in below attached code.
<?php
session_start();
include('header.php');
?>
<form name="cart.php">
<table>
<tr>
<th> ID </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<tr>
<td><?php echo $_GET['id']; ?> </td>
<td><?php echo $_GET['name']; ?> </td>
<td><?php echo $_GET['price']; ?> </td>
</tr>
</table>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$x=$_GET['id'];
$y=$_GET['name'];
$z=$_GET['price'];
$sql = "INSERT INTO products (id,description,price)
VALUES ('$x', '$y', '$y')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'"></form>
</form>
<?php
include('footer.php');
?>
<?php
session_start();
include('header.php');
$x=$_GET['id'];
$y=$_GET['name'];
$z=$_GET['price'];
?>
<form name="cart.php">
<table>
<tr>
<th> ID </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<tr>
<td><?php echo $x; ?> </td>
<td><?php echo $y; ?> </td>
<td><?php echo $z; ?> </td>
</tr>
</table>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (id,description,price)
VALUES ('$x', '$y', '$y')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'"></form>
</form>
<?php
include('footer.php');
?>
use the above code you will get your code working.
the problem is in query
so update that line as:
$sql = "INSERT INTO products (id,description,price)
VALUES ('".$x."', '".$y."', '".$y."')";

Categories