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.
Related
Simple question really.. If I have this:
$sql = 'SELECT id, name, address, city, phone FROM users';
$STH = $conn->query($sql);
$row = $STH->fetchAll();
if (count($row) > 0) {
$id = $row[0]['id'];
}
Will fetchAll ignore what I specifically chose to select and instead select EVERYTHING from the row, including large text fields etc.?
If so, what could be a workaround? I also need the row count
Fetch all simply means "fetch all rows into an array". It does not mean "fetch all columns, also the ones which I did not select" since this would be a quite awkward behaviour.
So, no, you need no workaround.
How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}
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.
What is the right way of checking if the required data is in the database?
What I use currently is,
mysql_query("SELECT anyfield FROM table WHERE field='$data'");
and then check the if any rows are affected.
But I dont really have any use with the extracted data anyfield.
Eventhough the resource usage is so minor here, what is the right way to check if data exists in a db without extracting any other fields from the table?
Let the database count and retrieve the count data from the query.
$result = mysql_query('SELECT COUNT(*) FROM `table` WHERE `field` = ...');
if (!$result) {
die(mysql_error());
}
if (mysql_result($result, 0, 0) > 0) {
// some data matched
} else {
// no data matched
}
$result = mysql_query("SELECT `field` FROM `table` WHERE `field` = '".$data."'");
if (mysql_num_rows($result)){
// Rows exist
}
OR
$result = mysql_query("SELECT COUNT(`field`) as count FROM `table` WHERE `field` = '".$data."'");
$row = mysql_fetch_array($result);
if ($row ['count']){
// Rows exist
}
I would ensure, if I was checking for data, that as little data was returned as possible.
Fetch one field (I usually do id) and ensure you use LIMIT, eg. LIMIT 1... assuming you only want to know if any record exists.
Because you're using a PHP variable to find a record, if it suits your situation, you could perhaps do a LEFT JOIN on the first SQL line that gets $data, but that might just as easily be overkill for what you need.
I am querying a large number of codes from my database, and need to have some validation before a user can input another code in to the database.
An example code would be this:
TD-BR-010212-xxxxxxxx
Where TD represents a promotion, BR represents a place, the numbers represent a date, and the rest are random.
My problem is that before the code is entered into the DB, I want to check to see if the date and place for that code already exists, as they should not be allwed to enter a code from the same place and date.
I assume it would be something within a loop as I already have:
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
But Im just not sure about the best way to check the strings..
You can use a MySQL LIKE clause to get entries in your DB that resemble your code.
Example:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
The '%' is used as a wildcard in SQL LIKE clauses.
You have two approach to solving this issue. Assuming you have access to alter the table.
Add a unique constraint to the table base off of the two columns.
Or Your approach by selecting all of the Location and Date, and see if it return any results.
SQL: SELECT COUNT(*) as counter FROM table where column = 'TD-BR-010212-%'
And check to see if counter return > 0;
I would use the LIKE statement in your SELECT and pull entries that start with the same promotion, place, and date. Unfortunately I don't know how your table looks so bear with me:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
try this query
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
If you can, you'll get better performance and easier coding if you break apart the code into different fields when you save the data in each row. That way you can write queries that specifically check values for the components pieces of the code - you can even set rules in the database (like UNIQUE) to ensure that some parts are kept unique.
Specifically, I'd suggest:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
Your first row would be ([...], 'TD','BR','2012-01-02', 'xxxxxxxx'). And queries would not require unpacking the formatted string - you could say things like "where promotion = 'TD' and place in ('BR','XX') ...". Simple, eh?