S
S
Sergey Nozdrin2013-09-14 11:05:49
PHP
Sergey Nozdrin, 2013-09-14 11:05:49

Explain strange INSERT behavior in mysql_query?

Hello!

I’m working on 1 project here and the following task arose: “Get a string with hash tags separated by commas from the user and write them 1 at a time to the database table. The table contains only 2 columns: ident and hash_tag. Ident is the identifier of what the hash tags refer to, and hash_tag is each individual hash tag ”

I wrote a script:

$idea_hash = "слово1, слово2, слово3";
$idea_count = 3


$mass = explode(',', $idea_hash);

foreach($mass as $n)

  {

mysql_query("INSERT INTO hashes (ident, hash_tag) VALUES('$idea_count','$n')");

  }


But at startup, only 1 word out of all is written to the database:

3 - word1

Although I would like to see 3 lines:

3 - word1
3 - word2
3 - word3

At the same time, the loop is clearly processed correctly. But for some reason, nothing is written to the database at steps 2 and 3.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stepan, 2013-09-14
@light204

Is the table empty? hash_tag is not unique by any chance?
1. For debugging, do

mysql_query("INSERT INTO hashes (ident, hash_tag) VALUES('$idea_count','$n')") or die(mysql_error());

2. Will you have a lot of tags? What for to duplicate the data also text? Isn't it easier to create another linked table with the tags themselves, and write ident, hash_tag_ident in the main one?

K
KEKSOV, 2013-09-14
@KEKSOV

Do you have a unique index on the ident field? And then you write three records with the same $idea_count value - in your case 3.
I hope the given code fragment is just a test, and not a piece from your project? Otherwise, this is one big hole in the security of the site;) Switch to using mysqli and prepared statements. This will dramatically increase the speed of query execution and save the project from a large number of security problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question