PHP and MySQL SELECT problem - php

Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);

If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].

First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode

Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.

Related

If statement condition not running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.
The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.
I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {
Does anyone see anything I am missing?
$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
$click_sql = "
SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$click_stmt = $con->prepare($click_sql);
$click_stmt->execute(array($user_id, $curPage));
$click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
$page_count = $click_stmt->rowCount();
foreach ($click_stmt_rows as $click_stmt_row) {
$setup_status = $click_stmt_row['setup'];
$page_total_count = $click_stmt_row['page_count'];
}
if ($page_count == 0) {
$click_insert_sql = "
INSERT INTO click_count
(user_id, page_url, page_count, setup)
VALUES(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE page_count=page_count+1;
";
$click_insert_stmt = $con->prepare($click_insert_sql);
$click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
}
else {
$click_update_sql = "
UPDATE click_count
SET page_count=page_count+1
WHERE user_id = ?
AND page_url = ?
";
$click_update_stmt = $con->prepare($click_update_sql);
$click_update_stmt->execute(array($user_id, $curPage));
}
Table
click_count
CREATE TABLE `click_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`page_count` int(11) NOT NULL,
`setup` int(5) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `page_url` (`page_url`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Since there is only the one user in the table, there is no record "to insert/update", therefore
ON DUPLICATE KEY UPDATE failed you silently.
A regular UPDATE will suffice:
I.e. and as an example:
UPDATE table SET col_x = 0|1 WHERE col_y = ? // (boolean 0-1)
Note:
If ever you wish to increase a column by counting later on, the syntax would be:
UPDATE table SET col_x = col_x + 1 WHERE col_y = ?
In regards to your asking about how you could improve on your code:
#Fred-ii- Thanks. Yes, it is working now how I want, but if there are ways to improve the code I am always willing to try to learn it. I just remembered people in the past saying that I didn't need the update query at all with the duplicate key update. – Paul
You could use named placeholders :name rather than ? since they are easier to keep track of, but this is of course a matter of opinion that I feel is also shared by many and not just myself.
Footnotes/credits:
I would like to also give credit to the following comment:
"If you always fall into update indicates that $page_count is not zero.. Try to echo() it to see maybe.. I would probably first try to add another user into click_count table and then it may become easier to see where it goes wrong.. – johnyTee"
where the OP responded with:
"#Fred-ii- I figured it out. I used johnyTee's advise and tried adding another user to the database manually and it wouldn't let me because of the unique index for the page_url column. I then removed the unique index from it and now it works perfectly. Thanks for the help! – Paul"
from PHP PDO doc http://php.net/manual/en/pdostatement.rowcount.php
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
if you need th number of rows in select you should use somethings like
$sql = "SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
It may be '0' (a string). You can use intval to convert it to an integer.
$page_count = intval( $click_stmt->rowCount() );
http://php.net/manual/en/function.intval.php
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
try like this:
$sql = "SELECT count(*)
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
//insert
}else {
//update
}
}

Auto-increment in mysql query

I need to populate several columns of MYSQL table with data from arrays. So one column corresponds to one array. I have used the following code to fill just one column with data:
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray) {
$myArray = array();
$myString = implode ("'), ('",$myArray);
$statement = "replace into myTable (ID, NAME)";
$statement .= "values (' ";
$statement .= $myString;
$statement .= "')";
$result = mysqli_query($db, $statement);
if ($result) {
return true;
}
}
I need the ID field to be populated by auto-generated incremented numbers. But I need these rows to be replaced with new values next time this form is submitted. For the "replace" to work the ID has to be the same as previously used, otherwise it will just create new entries.
Also, is there a better way to input arrays as columns in MYSQL table, other than one by one, cause I need all row values to match to each other and the ID should be unique and start from 0 or 1 next time the form is submitted.
Thanks for any help.
If you just want the row ID to be incremental you're making life hard for yourself! When you create the table in MySQL, use AUTO_INCREMENT on the ID, then you can just enter a NULL value for the ID in your code:
CREATE TABLE blah (ID INT NOT NULL AUTO_INCREMENT, name VARCHAR(50), PRIMARY KEY(ID));
$sql = "INSERT INTO blah VALUES(NULL, 'Adam')";
"Adam" will now have an ID of 1 :)

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

Create mysql table from PHP array

A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.
I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.
$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';
while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());
**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.
For one, this
'CREATE TABLE $table'
will NOT fill in $table, but will be LITERALLY
CREATE TABLE $table
use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql. There might be more, but probably easily discoverable trough mentioned debugging...
You apparenty have an extra trailing comma:
CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
col1 INT,
col2 INT,
-- ^ here
)
1
change the single quotes (') to double quotes (") for your query.
2
or use dot operator (.) to append php variable.
$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';
// Output
SELECT * FROM mytable
SELECT * FROM $tableName
You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.
If you are trying to get rid of the trailing slash you can also do this by using a counter.
$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
$query .=" ".$listing[0];
if ( $key+1 != $fieldsCount )
{
$query .=',';
}
}

How to get just inserted row from MySql to a php variable?

I'm using Zend Framework and MySql to create my web-application. My SQL-code is the following at the moment:
public static function newTestResult($testId, $accountId, $score, $deviation, $averageTime)
{
try
{
$db = self::conn();
$statement = "INSERT INTO test_results(test_id, test_person_id, score, standard_deviation, average_answer_time, created_at)
VALUES(" . $testId . ", " . $accountId . ", " . $score . ", " . $deviation . ", " . $averageTime . ", NOW())";
$db->query($statement);
$db->closeConnection();
}
catch(Zend_Db_Exception $e)
{
error_log($e->getMessage());
}
}
Now what I'm asking is: How can I get the just inserted row to a variable in PHP? I would want to get my hands on the id-value what MySql is creating automatically for the row.
Here is my table code:
CREATE TABLE test_results(
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_id int UNSIGNED NOT NULL,
test_person_id int UNSIGNED NOT NULL,
score float UNSIGNED NOT NULL,
standard_deviation float UNSIGNED NOT NULL,
average_answer_time float UNSIGNED NOT NULL,
removed boolean NOT NULL DEFAULT 0,
created_at datetime) CHARACTER SET utf8 COLLATE utf8_general_ci;
Take a look at the MySQL function "LAST_INSERT_ID()"
See also this forum for more detail on the methods available.
http://forums.phpfreaks.com/topic/188084-get-last-mysql-id-using-zend-frameworks/
In "plain" PHP, I usually use the mysql_ functions. The mysql_insert_id() function returns the key of the last row inserted. I'm not advocating this over using the Zend way, just giving context:
mysql_query("INSERT INTO ... query");
$id = mysql_insert_id();
Then reference that ID in writing other queries related to that inserted row.
This should give you the last insert id from the last query made.
$db->lastInsertId()
try this:
$query="SELECT id FROM test_results WHERE test_id=$testId";
$id=$db->query($query);
I assume this is what you're looking for, otherwise you can change the WHERE condition to whatever you need.
From the MySQL manual: "If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function." This refers to the C function.
In the PHP manual, you are suggested to use the PDO function instead. http://php.net/manual/en/function.mysql-insert-id.php PDO::lastInsertId
And apparently, "The insert() method on Zend_Db_Table will return the value of the last insert id." http://osdir.com/ml/php.zend.framework.db/2007-04/msg00055.html
To get last two records from any table you can use the following query
SELECT * FROM aa WHERE ID IN(
(SELECT COUNT(*) FROM aa),
(SELECT COUNT(*) FROM aa)-1
)

Categories