How to use count in php? - php

I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this
$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";
Why, the result of nors is 6 not 2, although I only have 1 data?

mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...
$no = "SELECT COUNT(ID) AS count FROM member";
$result = mysql_query($no);
$row = mysql_fetch_object($result);
$nors = $row->count;
You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.
edit: #andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.

If you're using this to generate the next ID number for a new member, you should look at making ID an auto_increment field instead - as it stands, it's possible that you'll get two members signing up at the same time, and both getting assigned the same ID

Replace this line
$nors = mysql_query($no);
By these lines :
$result_handler = mysql_query($no);
$result = mysql_fetch_array($result_handler);
$nors = $result[0];

If your id field is set to be an auto number you don't need to insert it. MySql will handle that for you. Anytime you add a new row the autonumber is incremented. If you delete a row the autonumber does not decrement.
If you currently only have 1 row but you've added and deleted rows then your insert will produce a row with an ID that is not consecutive.

Related

Row Count outputting - in front of the number of rows in table

Good day,
i have the following code in php
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid=$staffid";
$result4 = $pdo->prepare($sellast2);
$result4->execute();
$rowcount = $result4->rowCount();
echo $rowcount;
I am expecting that the row count would be one since this table only has one record in it.
The variable is outputting -1 and not 1 as expected.
What does the minus mean and why does it output a minus?
I am using Microsoft sql server management studio as the database.
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid='$staffid'";
use your $staffid in single quotes like i did, then pass a valid staff id and get your result

Get the last Id from database to a string/Int variable

I have to get the biggest id to a string or an int variable.
That is how I'm doing it:
$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
$list = mysql_query($sql) or die (mysql_error());
$lst = mysql_fetch_array($list);
$resId= $lst[0];
ResId is that variable.
Is this going to work?
Is there a better way to do it?
There is no AUTO_INCREACMENT!
If you don't auto increment or in any other way organize your id:s, there is no way to know which was the last one. (Unless you get the last inserted id when you're doing an insert query.)
Your query returns the greatest id, but if you haven't structured your code/table so that the greatest id is the last - then it won't return the last id obviously (oh well, it could).
As for your question if it will work. Why don't you simply try it out? You're much more likely to learn from trying your self than asking people for answers all the time.
If last id is the biggest id (as I see from your query), then you can also use:
$q = 'select max(id) as max_id from `b_iblock_element`';
$q_res = mysql_query($q);
$row = mysql_fetch_assoc($q_res);
$max_id = intval($row['max_id']);
And don't forget that mysql_* functions are deprecated and will be removed soon.

Getting Auto Increment multiple times

I'm hoping someone can help me figure out what I thought would be really easy.
I have a form that I dynamically add rows to. When I add the row, I want to display a unique value, and am using the MySql table primary key - called ID. Because there will be multiple users, I want to immediately reserve that ID, so it doesn't get reused. Since a user may decide to add another item to the list, and add another dynamic row, I want to repeat the process (get the new Auto Increment value from that table, and immediately reserve it).
Unfortunately, I continue to get the same ID value, even though I have confirmed the auto increment value has increased.
This is what I am using inside my "add row" function before I use the DOM Element to add the row:
$result = mysql_query("SHOW TABLE STATUS LIKE 'table'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment'];
$query = "INSERT INTO table (id, identifier1, identifier2) VALUES ('".$nextId."','".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
I have tried adding immediately before them the following in the hopes that it will blank everything and pull all new values:
$nextId = 0;
$row = "";
$result = "";
$query = "";
I am hoping someone out there can see something simple or suggest a better way that will work.
Thanks in advance.
Ok as your comment shows you have a slight mistake in your INSERT, try this:
$query = "INSERT INTO table (identifier1, identifier2)
VALUES ('".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id()+1; //you also need to +1 to get the next number
But there is NO guarentee that the next id will be +1 from the last.

select count doesn't count

I try to build a variable that integrates some other variable.
one of that will be the number of an auto-increment-field where later on an insert-query will happens.
I tried to use:
$get_num = $db/*=>mysqli*/->query("SELECT COUNT (*) auto_increment_column FROM table1");
$num = $query->fetch_assoc($get_num);
$end = $num + 1;
I don't have any update/insert query before that so I can't use
$end = $db->insert_id;
that's why i thought i can just count the numbers of the auto_increment rows and have my last variable that is necessary to build my new variable.
for a reason this wonT count the entries and outputs 0. i dont understand why this happens.
i really would appreciate if there is someone who could tell me what am i doing wrong. thanks a lot.
UPDATE
For everyone who likes to know about what's the goal:
I like to create a specific name or id for a file that later on will be created by the input of the fields from the insert query. I like to have an unique key. this key consists of an user_id and a timestamp. at the end of this generated variable it should be placed the auto_increment nr. of the query that will be placed in the table. so the problem is, that I create an variable before the insert query happens so that this variable will be part of the insert query like:
$get_num = $db->query("SELECT COUNT (*) FROM tableA");
$num = $query->fetch_assoc();
$end = $num + 1;
$file_id = $id .".". time() .".". $end;
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$file_id."','".$a."','".$b."','".c."')");{
hope now, it will be clear what I like to approach.
If you need an auto-incrementing column in MySQL then you should use AUTO_INCREMENT. It implements it all for you and avoids race conditions. The manual way you are trying to implement it has a couple of flaws, namely
If two scripts are trying to insert concurrently they might both get the same COUNT (say 10) and hence both try to insert with ID 11. One will then fail (or else you will have duplicates!)
If you add 10 items but then delete item 1, the COUNT will return 9 but id 10 will already exist.
try
SELECT COUNT(*) FROM table1

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories