how to get mysql id of number of effect row - php

I perform the mysql query to check if any number of row effected on the user input data with the help of mysql_num_rows($query). Only one row will effect always as I made some rows are unique. If one row effect, I want to get the ID of that Row. I means the auto increment ID of the same row.
The same row contains many fields, its better if I come to know how to get the entry of other fields.
Thanks stack for your solutions.

Have you tried SELECT id FROM table WHERE value=condition? If you query that you will get the id of the row that matches your condition. Replace id with the identifactor row, table with your table name, value and condition with your conditions.
$query = "SELECT id FROM table WHERE value=condition";
$result = mysql_query($query);
if ($row = mysql_fetch_row($result)) {
//$row contains valid information.
}
Btw: donĀ“t use mysql_* anymore, its deprecated, look at PDO or mysqli_*

$query = "SELECT mysql_id
FROM table";
$stmt = $db->prepare($query);
$stmt->execute();
$id = $stmt->fetchColumn();
You'll probably have to add a "WHERE" clause to your query statement and then pass the values into in array using a prepared statement.

just use mysql_insert_id();
this function after executing the insert query.
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
$lastInsertId=mysql_insert_id();
echo $lastInsertId;

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

How do I count unique rows in php pdo?

Here's my usual way of counting rows...
$query = "SELECT * FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
This will count all rows, even if I use a WHERE clause, it'll still count every row that meets that condition. However, let's say I have a table, we'll call it tokensEarned (that's my actual table name). I have the following data...
user_id = 1,2,4,5,8,8,2,4,3,7,6,2 (those are actual rows in my table - clearly, user 1 has 1 entry, 2 has three entries, etc.) In all, I have 12 entries. But I don't want my query to count 12. I want my query to count each user_id one time. In this example, my count should display 8.
Any help on this? I can further explain if you have any specific questions or clarification you need. I would appreciate it. Thank You.
The following query will yield the distinct user count:
$query = "SELECT COUNT(DISTINCT user_id) AS cnt FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo "distinct user count: " . $row['cnt'];
It isn't possible to get all records and the distinct count in a single query.
Whether you use the query above or you return all the actual distinct rows really depends on whether you need the full records. If all you need are the counts, then it is wasteful to return the data in the records, and what I gave above is probably the best option. If you do need the data, then selecting all distinct rows might make more sense.
You can use distinct in mysql to select only unique fields in your table.
$query = "SELECT distinct user_id FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
Change your query to the following, this way you only shows the unique user_id:
$query = "SELECT DISTINCT user_id FROM users";

PHP/MYSQL:Carry out UPDATE within SELECT query

There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}

PHP/MySQL query deleting data but not re-inserting

I have this PHP Code:
$stmt = $pdo_conn->prepare("DELETE from tickets_extra_emails where ticketnumber = :ticketnumber ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"]));
$cc_contact_line = '';
foreach(explode("\n", $_POST["cc_contacts"]) as $cc_contact_line) {
//then insert new if its not blank
if(filter_var($cc_contact_line, FILTER_VALIDATE_EMAIL)) {
//see if it currently exists
$stmt = $pdo_conn->prepare("SELECT * from tickets_extra_emails where ticketnumber = :ticketnumber and email_address = :email_address ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($records) == 0) {
echo 'insert '.$ticket["ticketnumber"].' - '.$cc_contact_line.'<br>';
$stmt = $pdo_conn->prepare("INSERT into tickets_extra_emails (ticketnumber, email_address) values (:ticketnumber, :email_address) ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
}
}
}
that makes each line of a textarea a variable in a foreach loop.
if i put lines in the textarea and submit the form, it saves the data but then if there is already data in and i submit the form, it removes it.
what do i have wrong in my code? I have commented everything it does
Theres a significant difference between MySQL INSERT and UPDATE.
You will need to check against the database where you are inserting to and use a query to check if there is data existing in that row. Based on that query you can restructure your insert statement to be conditional and switch from an INSERT to an UPDATE.
Deleting existing data will not allow you to re-insert into the rows, the rows are existing and therefor require UPDATE. However if you are removing whole rows then you can indeed re insert the rows. I see this as not entirely efficient, when you can utilize the efficiency of UPDATE to its benefit here.
AFAIK, fetchAll will fail if there are 0 rows, so you won't be able to run a count on the records. Do you have errors enabled or logged?
I see what you are trying to do and why you want to delete then reinsert, although maybe not the best approach.
Update: Apparently rowCount() shouldn't be relied on for selects, so I think the best alternative is to change your select query to select a count. This will always return a value as long as the query is valid so you shouldn't have to worry about the fetch failing. As you noticed below, I just changed the SELECT * to a SELECT count(*) so this will count how many rows match your constraints. Then use fetchColumn() to select the first column of the first row (the count).
$stmt = $pdo_conn->prepare("SELECT count(*) from tickets_extra_emails where ticketnumber = :ticketnumber and email_address = :email_address ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
$records = $stmt->fetchColumn();

Add up all rows where value is equal to ID

I've been looking up around for a couple tutorials of this and I've seemed out of luck. Basically, I have a database containing a winner's user ID (corresponding to the winners user ID) and a loser's ID. I am trying to create a members profile where it counts up all the rows the member has won. Here is what I have came up with:
$web = mysqli_query("select SUM(matches) WHERE WinnerUID='".$req_user_info['id']."'");
$web_sum=mysqli_fetch_assoc($web);
echo $web_sum;
Unfortunately, it doesn't display any number. Can anyone help?
I think you're looking for COUNT() not SUM(). And you didn't include a table name. Also remember that mysqli_fetch_assoc() returns the row as an array, it doesn't return the first column's value. Also, mysqli_query() requires the connection as the first argument.
$web = mysqli_query($conn, "select COUNT(*) as total FROM matches WHERE WinnerUID='".(int)$req_user_info['id']."'");
$row = mysqli_fetch_assoc($web);
echo $row['total'];
Don't concatenate variables into your SQL. Use a Prepared Statement with bound parameters. I have casted your ID as an (int) in the above code, which is a quick fix but you should switch to a Prepared Statement.
Prepared Statement example (object oriented interface instead of procedural):
if ($stmt = $conn->prepare("select COUNT(*) from matches WHERE WinnerUID = ?")) {
$stmt->bind_param("i", $req_user_info['id']);
$stmt->execute();
$stmt->bind_result($web_sum);
$stmt->fetch();
echo $web_sum;
$stmt->close();
}

Categories