Select a value from table and reserve it - mysql

Low level question but, I understand that you can select elements from a table using:
$sql = "SELECT blah FROM TABLE WHERE this = 'something' ";
But when I try to select a specific value from my table, where let's say a user has no tries left so if I try to grab how many tries they have left with:
$sql = "SELECT tries FROM table WHERE user = 'something'";
How would I grab that value specifically if it was 5 or 9? I tried setting a variable equal to something I $sql off my table but it doesn't grab the value.
Edit
I have a database that has a table called Item which contains: id, name, value, and stock of a particular item. If a user wants to order that item I will first check it if's in stock with a function, to see if it is not in stock then a error message is printed, otherwise accept the order.
Extremely primitive since I'm just trying to get grab the stock value first.
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' .$query.''; //test purposes
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
echo '' .$sql2. ''; //test purposes
whats the correct way to assign the value from that specific stock to a variable?

If you want to grab rows with a set of possible values you can use 'IN' such as:
Get all columns from users table where users have 5 or 9 tries:
SELECT * FROM users WHERE tries IN('5', '9'); or
If you want to select where the user has no tries left, assuming the tries column is a numeric type you can look for rows with 0 tries:
Get all columns from Item table where stock is 0:
SELECT * FROM db_inv.Item WHERE stock = '0';
Get all columns from users table where tries is 0:
SELECT * FROM users WHERE tries = '0';
As for your php code you should be able to do the following:
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' . $query; //test purposes
$mysql_handle = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database server");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
$results = mysqli_query($mysql_handle, $sql1);
if (!empty($results) && mysqli_num_rows($results) > 0) {
while($rec = mysqli_fetch_array($results)) {
echo $rec['item_stock'];
}
}

Related

SQL SELECT CASE with Where From Looping Value

I have 2 tables :
table names transaction and detail customer
transaction table fields are idtrans and idcust.
detail customer fields are idcust and custname.
i have Problem with my php syntax, i want select table with condition from value lopping, here's my code:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from transaction";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sqlid="select * from detailcust where idcust='$row[idcust]')";
$resultid= $conn->query($sqlid);
if ($resultid->num_rows > 0){
while ($rowid= mysqli_fetch_array($resultid)){
$custname=$rowid["custname"];
echo $custname;
}
result name always first idcust value.
You seem to want the names of customer that have at least one transaction. If so, no need for loops and multiple queries. You can get the result you want with just one query:
select c.*
from detailcust c
where exists (select 1 from transaction t where t.idcust = c.idcust)

Add 2 numbers together, one from a database result and the other from post array

I'm trying to add 2 numbers together. The first number is from the database say it's 150 it comes from the $sql1 and the second number comes from the form and is in the POST array say it's 25. Once the $sql2 is run the number in the database should be 175 but it's still 150, any ideas on what i'm missing/doing wrong?
$sql1 = "SELECT points FROM users WHERE userID = ?";
$qc1 = $pdo_conn->prepare($sql1);
$qc1->execute(array($_POST['userID']));
$result = $qc1->fetch(PDO::FETCH_ASSOC);
$points = $result + $_POST['addPoints'];
$sql2 = "UPDATE users SET points = ? WHERE userID = ?";
$qc2 = $pdo_conn->prepare($sql2);
$qc2->execute(array($points, $_POST['userID']));
Based on your code, the $result variable is going to return the response from the database as an array. Thus, in order to get the number, you need to pass the field name from your SELECT statement.
Therefore,
$points = $result + $_POST['addPoints'];
should be:
$points = $result['points'] + $_POST['addPoints'];

Mysql Update, 2 databases

I have 2 MYSQL tables and when I pick up dates from table A which contains only 1 column and lets say 10 rows with dates
$result = mysql_query("SELECT * FROM A");
$row = mysql_fetch_assoc($result);
And after I want to UPDATE another table B with using this dates from table A mysql_query("UPDATE B SET something='1' WHERE name='".$row['name']."'")
So i need to update the second table, but its updating just once with first date from table A, and other 9 its ignoring. So my question is, how to make updating of second table with each date from 1 table?
You need to run a the updates in a loop. After executing your query
$result = mysql_query("SELECT * FROM A");
and verifying that it has succeeded (make sure $result is not null), instead of fetching one row, use a loop:
while($row = mysql_fetch_assoc($result)){
// perform calculations & assignments with the $row elements
$result2 = mysql_query("UPDATE B SET something='1'
WHERE name='".$row['name']."'");
if(! $result2){
echo "update failed";
}
// Any other stuff you need to do
}
Alternatively:
If the something in the update is the same for all the rows, you can change your first query to give you a coma-separated string of names:
$result = mysql_query("SELECT CONCAT("'",GROUP_CONCAT(name SEPARATOR "','"),"'")
AS all_names FROM A");
This way, you receive only one row, and you can then use it in your second query:
$result2 = mysql_query("UPDATE B SET something='1'
WHERE name IN (".$row['name'].")");

Trouble updating a particular user in a mysql database

im trying to update a particular user that is logged in using UPDATE mysql command, but instead it is going to the first user that is in the database itself, if you can help id appreciate it
Edit: Im wanting to increment the number of 'items' that a user has, but for the code below its only going to the first user in the database
<?php
session_start();
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("UPDATE users SET item = item + 1 ",
mysql_real_escape_string($_POST['item']));
mysql_query($query);
?>
Your sprintf() call has a parameter, but no placeholder:
$query = sprintf("UPDATE users SET item = item + 1 ",
mysql_real_escape_string($_POST['item']));
Probably this is supposed to be something like the following, assuming an INT column named item
$query = sprintf("UPDATE users SET item = item + 1 WHERE item = %d ",
mysql_real_escape_string($_POST['item']));
UPDATE
If you are trying to target a specific user only, then you need that user's id or username in $_POST instead of item. You'll need to post the output of var_dump($_POST) for us to see just what values you've received in post.
Assuming a string username, use:
$query = sprintf("UPDATE users SET item = item + 1 WHERE username = '%s' ",
mysql_real_escape_string($_POST['username']));
you need some kind of where clause. specify which user you want to actually update with extra conditions.
YOu need to know which user you want to update...
$query = sprintf("UPDATE users SET item = item + 1 WHERE userId="+ $userId,
or something like that...

how can I connect these two tables in sql?

i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!