Search value in table, if the value is not found, auto insert - php

Is it possible to search for a value in MySQL and if the value is not found, automatically insert that value?
For example:
This is my table. The id is auto increment, the case id is inserted by me
when I search for a number on my search box. If that number is not inside the table, it will auto insert it into the table.
id| case id
1 | 324
2 | 789
3 | 314
when me search 123 on my search box.that number of 123 is not in my table so that number of 123 will auto insert into my table.
id | case id
1 | 324
2 | 789
3 | 314
4 | 123
Is this possible?
here is my code
mysql_select_db($database_connection_db, $connection_db);
$query_viewAduan = mysql_query("SELECT No_KP, COUNT(*) FROM aduan_tidak_hadir WHERE No_KP LIKE '%".$no_kp."%' GROUP BY No_KP;");
while ($row = mysql_fetch_array($query_viewAduan))
{
if (!$row['COUNT(*)'])
{
echo 'satu';
}
else if ($row['COUNT(*)'] == '1')
{
echo 'dua';
}
else if ($row['COUNT(*)'] == '2')
{
echo 'tiga';
}
}

Yes this is possible but not with simple sql statements. This has to be done with an extension of sql called PLSQL. If you know PLSQL then continue reading or otherwise stop right here and learn it befor you read this full answer.
Here's the code for you question:
declare numb my_table.case_id%type
begin
select case_id into numb from my_table where numb=case_id;
exception
when no_data_found then
insert into my_table values(/*you said the id auto_increments so I'm leaving this one out*/,numb);
end;
Since I didn't know the name of your table I just called it my_table. Try this and it should work.

A quick note before I move to an answer. Any time you ask a question, whether it be on the web or to another person, you should have tried something already. This is true for any subject. If you want to drive your car, you must first try to start it. It might be obvious that you tried that, but in a more technical subject, we need to know that you in fact did try something, and that what you tried did not work. A lot of times these questions get asked because the users have in fact tried nothing at all. It is important that you try something, because that is your real learning experience. Just following a set of instructions given to you here will not help you in the future.
Now on to helping you figure out your problem. You have flagged your question as a PHP and MySQL question, which suggests that you don't need to do it in a single MySQL query. I won't give you the code to do it, but I will point you in a direction for some sample code.
Let's break down your question into the actual steps:
Search value in table
This is the first part of your question. This is a basic select statement. I'm sure you can figure it out. If not, google for MySQL select.
if the value is not found
This is the second part of your question that essentially defines what you must do in PHP. You need to check if the value was not found. You need to look at the results of select statement from your search value in table step and determine whether or not it was empty or contained results.
auto insert
At this step, based on your last step if the value is not found, we can determine whether or not we should insert the value. For instructions on how to do an insert, Google mysql insert.

Related

SQL add a counter row

I'd like to add a counter to my website.
I am currently using php and mysql.
An example would be a total count of people who logged in my website.
The structure would look like this
|Total User Logins|
| 1|
If a user logs in though, I'd like to do this
|Total User Logins|
| 2|
How would I do this? At the moment it only creates a new row, which is not what I am after.
This is what I tried to do:
mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE 1 ");
^ this works on the phpmyadmin panel. But does not work on the php script.
Thanks
You need to be more specific in the WHERE clause, as to the specific column that is to be updated. That's why your code failed you and is creating a new row each time.
I.e.:
mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE column_x = 'y' ");
Side note: column_x could be User as per what you posted for column names. I didn't see one called Success. The y is an example also. Use the value from the given row you wish to update.
This is purely an example, given you seem to have left out some important details.
By the way, the api you're using is quite old. It is recommended that you move over to either the mysqli_ or PDO api as soon as possible and preferably with a prepared statement. This will help safeguard against a possible SQL injection should user input be involved or any other method such as an href through a GET method.

configure mysql database to save progress

I am new in forum, and need some help to do one functionality for my unity game. I am trying to save the progress of the player in one mysql database, like this:
userid level stars
29 1 2
29 2 1
45 1 3
50 1 2
50 2 3
50 3 1
29 3 3
so the script send the userid provided by the user registration in the begining of the game. and for each level he complete, the script send the number of the level, and the amount of stars collected in the level..
the problem and question is, how I configure this in the php script and mysql database to save the information only once? because if the player with the id 50 play the first level, will add a line with the information, but if the same player play the first level again and change the amount of stars, I dont want a new line, just update the stars amount.
I take a look in the INDEX, UNIQUE, PRIMARY, FULLTEXT, SPATIAL functions but dont figured out what is the correct combination and how to put in the php script, and take a look in other questions in the forum but nothing like this.
thanks for the help!
I recommend you use http://redis.io/ (in-memory data structure store, used as database, cache and message broker) to save progress in the games.
First you want an unique index on the combination (userid, level) and then you want to do an update if the combination exists and an insert otherwise.
For how to create the unique index please take a look at How do I specify unique constraint for multiple columns in MySQL?
For how to code the SQL query to do update/insert please take a look at SQL: If Exists Update Else Insert
The article above uses Microsoft SQL syntax. In PHP you can code this by issuing the query and then using mysql_affected_rows to see how many rows where affected. If 0 rows where affected then you issue the INSERT query from PHP.
in pseudo code you need to do something like this in SQL.
UPDATE $table set column=value WHERE id=$ID
Hi brayan actually the problems is that no one will write code for you, you have to do it yourself. I guess you are unaware with SQL i.e., you asked that
how I configure this in the php script and mysql database to save the
information only once? because if the player with the id 50 play the
first level, will add a line with the information, but if the same
player play the first level again and change the amount of stars, I
dont want a new line, just update the stars amount.
Anyhow You first required some basic understanding of SQL and PHP with Unity. I will recommend you this Guide Server_Side_Highscores of unityWiki it help you to make database and server logic intergartion with PHP.
Now for your Second important part of question.
You have to update user code after each level completion.Or you can simply ask to user about socre save.
Before inserting new record into the database you have to check that userId with level id alread exist or not. some thing like this
Select userid, level, stars
from youTableName
where userid = ?
and level = ?
if the above query return empty response then you simply need to add the record
INSERT INTO table_name (userid, level, stars)
VALUES (value1,value2,value3);
Otherwise you have to update that specific column.

Multiply column with same content, make them count as "one"

About
I have this table in my database holding some information saved with a user id and time.
| CONTENT | USER ID | TIME |
| text | 1 | 1405085592 |
| hello | 2 | 1405085683 |
| hey | 1 | 1405086953 |
This example could be a data dump from my database, now as you can count there is "three" rows. However I only need to know how many users there have some information in my database. Therefor the result I'm really looking for is "two", because only two users have information in the database. User ID 1 is owning both "text"(1) & "hey"(3) where user ID 2 haves "hello"(2).
In short
I want to count how many users (regardless how many rows of information they have) there are inside my database.
** What I tried **
I tried to fetch every single row into an array and then using array_unique to count them together, works fine but I do not see this as a clean and best way to do this.
Then what?
I could use the array_unique and just use count to see how many rows there are, but I'm looking for something more clean. I tried to search for this, but I'm not actually sure what I should search for in term to hit something I'm looking for. After being stuck and though I wanted to learn something new, I wanted to post this problem here.
Note
I hope you guys can help me, I have tried to make it clear what I'm looking for and what I tried. If not please let me know. Sorry if some of the above contains misspelled words, incorrect grammar or is badly explained. I do not speak English daily, but I try my best.
You are looking for the DISTINCT keyword. It returns the count of unique values of a column:
SELECT COUNT(DISTINCT user_id)
FROM your_table
See example on SQL Fiddle.
This query:
SELECT DISTINCT user_id FROM table
will return just one row for every user in the table.

MySQL error after reordering ID column

I need some help with a particular table in my database. I tried reordering a column (id) of integers, but now the present values of renamed id are taking the values of the former value.e.g
If: (before re-odering)
------------
id Name
2 Stack
3 Over
4 Flow
------------
A link like page.php?id=3 gives a value of OVER which is correct
After re-numbering
------------
id Name
1 Stack
2 Over
3 Flow
4 Name
5 Last
------------
When I use a link like page?id=3 i still get OVER, which is not correct. Also the new id = 5 does not return any value.
Please where could the problem be ?
Update
When I tried from phpMyAdmin "SELECT * FROM tap_bios WHERE tap_bios_id = 3 I get Over instead of Flow.
...are you sure you don't have that request cached in your browser? Try clearing the cache and rerunning the query. Also, try logging the queries and copy/pasting them into a query browser. If you get the same unexpected results when dealing directly with the database while using the queries you think are correct, it's a database issue that will require further investigation. Otherwise, you may have a caching issue happening somewhere else in the system.

PHP query - How to compare two columns from different tables to match one column

Sorry, I wasn't sure exactly what title to give this and have not been able to find any other posts regarding it though I am sure it must not be very difficult - I am just not aware of how to do it.
in a php query, I need to compare one column in my database with another column (on a different table) to see if they match (using == ). However, the second column on the other table that needs to be matched can only be determined by a third column located on the same table as the first column came from.
Before I make it sound more confusing that it probably is, here is a basic outline of what I need to achieve:
if ($this->prefix == $user->special_id ??? $table2['CODE']) {
I don't know what to put where the ??? is..
special_id is generated from table2 and on table two there is also a column called CODE - CODE is what is used to make the prefix on table 1
TABLE 1
+--------+------------+
| prefix | special_id |
TABLE 2
+------------+------+
| special_id | CODE |
Some how I need compare the CODE from table2 and see if it is equal to the prefix on table1.. the link being special_id on both tables
(CODE and prefix can often match which is why I need to check it)
Sorry if my explanation isn't clear enough, any suggestions would be much appreciated - I just don't know how to write the code between special_id and $table2['code'] to make them operate together so to speak.
Thank you for reading.
EDIT:
I have "A" version working, and although it normally achieves the right results for me, there are some situations when it doesn't (due to other factors), so I am still hoping to keep a similar type of line:
(this one does bring results but the results are not always correct (and I don't want to compare special_id to special_id, I need to compare prefix to the special_id's code from the other table) so if anyone can still help please make a suggestion)
if ($this->special_id == $user->special_id&&$this->prefix==$table2['CODE']) {
EDIT: THE ANSWER
This would have been hard for anyone to answer without seeing all the code, but in case anyone happens to have a similar issue, here is the answer:
if ($this->prefix == $table2['CODE']) {
Half of cj's answer was right so have given the correct answer to him.
Looks like you are using an ORM of some sort. I don't recommend using an ORM in PHP, but if that is what you are doing, I'd try something like this:
if ($this->prefix == $user->special_id && $this->prefix == $table2['CODE'])
{
}
Or this, for clarity:
if (($this->prefix == $user->special_id) && ($this->prefix == $table2['CODE']))
{
}
In terms of MySQL statement (which I would recommend you using), it would look like:
SELECT t1.special_id as special_id
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.special_id = t2.special_id
WHERE t1.prefix = t2.CODE

Categories