With PHP subtract a quantity from an mysql table - php

I am trying to do a php code that subtract -1 of quantity stored in a mysql table named ''caffe''.
The table start with 10 and if php is executed with value caffe a quantity in table will be updated.
Will be good some lines of code so i can understand how it work.
read value from url: http://mypage/getdata.php?value=caffe
read value from database table caffe
subtract -1 from the table
update the value of mysql table caffe
<?
$servername = "localhost";
$username = "xxx";
$password = "";
$database = "my_ufficina";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
$txt = $_GET['value'];
if ($txt == caffe)
$count = 1;
echo $count;

I would try something like that :
if ($txt === 'caffe') {
// get Caffe value :
try {
$currentCaffeValue = $conn->query("SELECT yourCaffeValue FROM yourTable");
} catch (Exception $e) {
echo 'db read failed : ', $e->getMessage();
}
// do your stuff then update Caffe value :
try {
$conn->query("UPDATE yourTable SET yourCaffeValue = yourCaffeValue - 1");
} catch (Exception $e) {
echo 'db update failed : ', $e->getMessage();
}
}
And by the way, you should sanitize values from $_GET before using it : http://php.net/manual/en/function.filter-input.php

Related

copy data from 1 table to another table with checking for equal data

I have been working on migrating a webshop. The company that did this did something wrong and I want to fix it myself.
The problem is:
I have 2 tables 1 from the old webshop (let's call this one A) and one from the new one (and we call this one B).
Now the short description needs to be copied from table A to table B. The column name in table A is meta_description and in table B it is description_short. but I do not want to just copy and be done. Because when I do that everything will not be in order. Cause both tables are sorted differently.
I got this far:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO pskd_product_lang (description_short)
VALUES ($desc)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
where $desc is made here:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM oc_product_description";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$name = $row["name"];
$desc = $row["meta_description"];
echo "<tr><td>".$name."</td><td>".$desc."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
as you can see the target table (B) is called pskd_product_lang
The source table (A) is called oc_product_description I tried were statements and a lot of other things I found on the internet but nothing worked...
If someone could help me out or point me in the right direction I would be grateful!!
Thanks in advance

PhP MySQL get ceratin items from database and echo them

I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}

how to get diffrent data from single column in mysql and php

i want to store multiple data with comma separated in single column and get back data with the help of php in different different line
like in column view it will looks like this-- toothbrush-1234,glass-1234,
in up there 1234 is product id
i want to get this data in php with separated values each line with its all details.
like
<?php $sql="select product_name form products where product_id=1234" ?>
So is it possible to get data and separat it by - and , from single column.
You want to display your comma separated data into separate rows. You can try this.
<?
//Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select product_id,product_name form products where product_id=1234";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$yourData = array();
while($row = $result->fetch_assoc()) {
$yourData[$row['product_id']] = explode(",",$row['product_name']);
}
if(count($yourData) > 0){
foreach ($yourData as $key => $value) {
foreach ($value as $productname) {
echo "Product ID >> ".$key. " -- Product Name >> ".$productname;
}
}
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Side Note: If you are using mysql_* in your application than i suggest you to use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7.

mysqli update not updating although no error

I am trying to adapt my code, which works in a SELECT, to perform an UPDATE. Here, there is no error, but it does not update anything, it even does not even enter the loop. It is supposed to update the room type for the chosen days ($value).
I echoed all values to check them up and they are correct.
$bdd = mysqli_connect('localhost', 'root', '', 'webpage')
$roomty = 1;
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
foreach ($_SESSION['datesBooked_1_month'] as $key => $value)
{
$stmt = mysqli_stmt_init($bdd);
if ( mysqli_stmt_prepare( $stmt , "UPDATE '".$_SESSION['tab_from_month_year']."'
SET '".$_SESSION['roomtype_x']."'='".$_SESSION['roomtype_x']."' + ? WHERE day = ?"))
{
mysqli_stmt_bind_param( $stmt ,'is', $roomty , $value );
mysqli_stmt_execute( $stmt );
mysqli_stmt_close($stmt);
echo " Booked !<br /> ";
}
}
Please try the following code with the new MySql driver of PHP.
you put the quote for a integer value, that is wrong
do you named column with numbers? That is not comfortable.
Are you sure that $value is a string?
Why did you use $key => $value in the foreach loop?
Here the code:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=webpage;host=127.0.0.1';
$user = 'root';
$password = 'dbpass'; #put here yor password
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach $_SESSION['datesBooked_1_month'] as $value) {
#I hope that following variables don't contain space
$query = "UPDATE " .$_SESSION['tab_from_month_year'];
$temp = $_SESSION['roomtype_x'] + $roomty ;
#you wrote that $value is a string, are you sure?
$query .= " SET ".$_SESSION['roomtype_x']. "=$temp WHERE day='$value'" ;
$dbh->query($query);
}
I found out, the problem was the single quotes before the double quotes. It seems to be working very well with only double quotes like this :
if ( mysqli_stmt_prepare( $stmt , "UPDATE ".$_SESSION['tab_from_month_year']." SET ".$_SESSION['roomtype_x']." = ".$_SESSION['roomtype_x']." + ? WHERE day = ?"))
If this is the full code you need to select a database, currently the statement is being sent to the server but not to any database, there for you get no errors. You should use:
mysqli_select_db("You database goes here");

how to connect ( pull data ) from one server to ( insert into - create table ) another server using pdo in php-mysql , possibly fetch ?

Can anyone please tell me how could I fix this code below ? so that I can pull data from host1 (database x , table 1 ) to create table in host2 ( database dx, table2 ),
What am I missing here ? someone tell me to use prepare then fetch array then insert into table2 , can any one show me , how to ?
here's my code
<?php
echo 'Database Connection <br>';
$hostname = "host1";
$hostname1 = "host2";
$username = "myname";
$password = "mypassword";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=x", $username, $password);
echo "Connected to database x<br>"; // check for connection
$dbup = new PDO("mysql:host=$hostname1;dbname=dx", $username, $password);
echo "Connected to database dx<br>"; // check for connection
/*** The SQL SELECT statement ***/
$sql = $dbh->query("select name, choices from table1")or die(print_r($dbh->errorInfo(), true));
$sql1 = $dhup->query("CREATE TABLE api(
`name` VARCHAR(40) NOT NULL,
`choices` VARCHAR(255) NOT NULL )")or die(print_r($dbh->errorInfo(), true));
foreach ($sql as $row)
{
$dbup->exec("insert into table2('name','choices') values('" . $row['name'] . "','" . $row['choices'] . "')") or die(print_r($dbup->errorInfo(), true));
}
// /*** close the database connection ***/
$dbh = null;
$dbup = null;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
Thanks
I noticed you're not consistently spelling "dbup" the same way.
In:
$dbup = new PDO...
You used d'B'up.
In:
$dhup->query("CREATE TABLE...
You used d'H'up.
Maybe this is a simple case of a typographical error?

Categories