简体   繁体   中英

I can't add IPs to my database. Why?

So what I want is to be able to add different IPs to my database. What I do is:

if ($stmt = $conn->prepare("UPDATE csgo_servers SET ips = ips + '$anip' + '|' WHERE id = ?")) {
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $stmt->close();
    echo "IP Added!";
}

I want to have different IPs in a Longtext column like that: 32.12.53.12|42.12.41.2|42.1.6.3.7 . The problem is when I do it it only adds the first let's say 32.12 of the IP and without the |. Any help?

Structure of your table
Like it was mentioned in the comments, having character-separated values in a database like that (in your case, the separator is | ), is a bad idea . You should normalize your database - have more rows instead of doing that. It'll be way easier to work with!

Why this won't work as it is
MySQL can't add strings together with + (like you do in JavaScript). That's telling MySQL that you want to do mathematics (adding integers, eg 1+1 ). That means that you're silently converting to integers, which is why you're only seeing the first part of the IP (the first part before the period . is an integer, the rest is turnicated).

Solution
You can use the CONCAT() function to achieve what you want - although like mentioned above, I strongly advise against this structure , this will add the last IP with a separator | .

With also adding the new IP with a bounded placeholder (like you bind the ID), the new code would look like this. You should always bind every variable going into the query, otherwise it's a little pointless.

if ($stmt = $conn->prepare("UPDATE csgo_servers SET ips = CONCAT(ips, '|', ?) WHERE id = ?")) {
    $stmt->bind_param("ss", $anip, $id);
    if ($stmt->execute())
        echo "IP Added!";
    $stmt->close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM