MySQL and PHP, is there something wrong with my syntax? - php

Currently, my query (in my PHP script) is
mysql_query('INSERT INTO julian.guestbook (name, message, email, date) VALUES ("Julian Davis", ".'$newmsg.'", ".'$newmail'.", NOW());');
and it returns an error. A moment ago (before I jumped through that hoop with the variables) (and yes! I made sure to sanitize them!), it returns a broken page. Even with error reporting on, it won't report an error. If you just pass the name of the variables, it will submit
mysql> SELECT * FROM julian.guestbook;
+--------------+---------+----------+---------------------+
| name | message | email | date |
+--------------+---------+----------+---------------------+
| Julian Davis | $newmsg | $newmail | 2015-09-18 17:53:50 |
+--------------+---------+----------+---------------------+
but I want my (sanitized) data from my HTML form earlier in these boxes. I can't seem to get PHP to pass these strings along without messing something up in MySQL and not telling me anything it's doing.

The . that you used for concatenating needs to be outside the string.
mysql_query('INSERT INTO julian.guestbook (name, message, email, date) VALUES ("Julian Davis", "' . $newmsg . '", "' . $newmail . '", NOW());');

Related

Use like with PDO on JSON-String

Actualy I know how to use LIKE statement with PDO
Now I have a DB-Table called e.g. foobar
foobar contains a JSON-String like:
{"firstname":"foo","email":"aaa#aaa.aa","lastname":"bar"}
Now before I call my INSERT on the table I want to check if the Email is already in use.
$pdo->query("SELECT * FROM myTable WHERE foobar LIKE ?", array('%' . $email . '%'));
as you can see, I pass the email into the pdo query.
Notice ->query is my custom function that handles some stuff. In this case its not important to know what happens.
The problem I have is:
If the entry like above exists then its not possible anymore to add an email thats like:
aa#aaa.aa
^^....only two A's
So I thought I can simply change
array('%' . $email . '%')
to
array('%"' . $email . '"%')
but this doesnt work. Is there a way I can check the whole string part ?
{"firstname":"foo","email":"aaa#aaa.aa","lastname":"bar"}
If you can't break the JSON fields into their own columns, then I would suggest a JSON column type. It's native to MySQL, super fast for JSON of this size, and no more difficult to use than something like jq on the command line.
If that's not an option, I would use a REGEXP:
mysql> select * from foobar;
+-----------------------------------------------------------+
| json |
+-----------------------------------------------------------+
| {"firstname":"foo","email":"aaa#aaa.aa","lastname":"bar"} |
| {"firstname":"FOO","email":"aa#aaa.aa","lastname":"BAR"} |
+-----------------------------------------------------------+
mysql> select * from foobar where json regexp '"email":"aa#aaa.aa"';
+----------------------------------------------------------+
| json |
+----------------------------------------------------------+
| {"firstname":"FOO","email":"aa#aaa.aa","lastname":"BAR"} |
+----------------------------------------------------------+
1 row in set (0.00 sec)
This is serviceable, but hardly bullet-proof and, to borrow an excellent turn of phrase, will murder performance on anything but trivial row sets.

Using prepared PDO statement with PHP - binary numbers

I'm relatively inexperienced with php, pdo and sql. that being said, I have been working on a small project and while most things are working as intended i'm having some issues.
take the following information from the mysql (mariadb) database
| Field | Type | Null | Key | Default | Extra |
| age | bit(6) | YES | | NULL | |
In the PHP I have a simple form where you enter your age, eg. mine is 33.
$age=decbin($_POST['age']);
this correctly shows 100001 when i echo $age.
using my (possibly horrible) pdo statements
$stmt = $DBH->prepare("INSERT INTO Recruit(recruit_id, name, age) VALUES(:recruit_id,:name,:age)");
$stmt->execute(array(':recruit_id' => $recruit_id, ':name' => $name, ':age' => $age));
recruit_id and name both show up without issue, but age always populates as 111111 regardless of what i enter as the age.
I've tried doing cast(:age as binary(6)) with the same results. I'm simply at a loss of how to accomplish this task.
*****corrected typo in the database paste*****
i have changed age to an integer, however, i still yes a couple on/off options that are stored as binary(1) and the same issue presents. php can show the value as a 1 or 0 correctly, but when sent to the db, it is always a 1. (age presented a good example as all 6 bits were 1)
UPDATE: After further research, it sounds like my previous answer wont work for the method you are using as parameters passed to the execute function are all treated as PDO::PARAM_STR. You'll want to bind them all separately and use PDO::PARAM_INT for the age variable. Like so:
$stmt = $DBH->prepare("INSERT INTO Recruit(recruit_id, name, age) VALUES(:recruit_id,:name,:age)");
$stmt->bindParam(':recruit_id', $recruit_id, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
(PREVIOUS ANSWER)
From MySQL Reference:
To specify bit values, b'value' notation can be used. value is a binary value written using zeros and ones. For example, b'111' and b'10000000' represent 7 and 128, respectively.
So I'd try this instead: $age = "b'".decbin($_POST['age'])."'";

Getting all projectname values with certain name in a table

So I am creating a website for me and my friends so we can work on projects with each other (Like Google documents), and I am trying to create a thing so we can choose what project we want to work on. Currently I am having trouble getting the names of the projects from the MySQL table.
Here is what I have tried to get the names of the projects
$projects = mysqli_query($link, "SELECT * FROM table WHERE name='". $username ."'");
$projects2 = mysqli_fetch_assoc($projects);
$projects3 = $projects2["projectname"];
And here is an example of the MySQL table
+---------+------------------+------------------+------------------+------------
-+
| name | htmltext | csstext | jstext | projectname
|
+---------+------------------+------------------+------------------+------------
-+
| cow9000 | testing is cool! | testing is cool! | testing is cool! | test
|
| cow9000 | testing is cool! | testing is cool! | testing is cool! | test2
|
+---------+------------------+------------------+------------------+------------
As you can see there are 2 documents that the owner owns, but when I try printing out $project3, it only gives me "test". How would I change my code to get all projectname values?
Sorry if this is confusing, it is hard for me to put it into words. Also, please do point out errors in my code as I only have a couple days of experience in PHP and MySQL (But I am finding that PHP and MySQL is very, very easy for me.)
You already have all of those values. You just access them like you did projectname, by using the name of that column as the key in the $projects2 array:
$projects2 = mysqli_fetch_assoc($projects);
echo $projects2["name"]; // cow9000
echo $projects2["htmltext"]; // testing is cool!
echo $projects2["csstext"]; // testing is cool!
echo $projects2["jstext"]; // testing is cool!
If you want the second row you need to use a loop:
// Prints each row in the order they were retrieved
while($projects2 = mysqli_fetch_assoc($projects)) {
echo $projects2["projectname"]; // test and then test2
}
You have to iterate through the returned data, for example like this:
while ($projects2 = mysqli_fetch_assoc($projects)) {
echo $projects2["projectname"];
}
First it will return test, second test2

PHP & MySQL: Select account from database which hasn't been refreshed for more than 2 minutes

I have something like this in my database:
ID | ACCOUNT | PASSWORD | LAST_REFRESH
1 | acc1 | pass1 | 1386506130
And in my PHP script I have this:
$allowed_time = time() - 121;
$query = mysql_query('SELECT account FROM accounts WHERE last_refresh >= '.$allowed_time.'');
But if I try this query, nothing will be returned, even if $allowed_time is bigger than last_refresh in the database.
Try:
$query = mysql_query("SELECT account FROM accounts WHERE last_refresh >= $allowed_time");
Using double quotes for your query will allow you to use variables without concatenating them. Also, you're trying to compare a number and originally you were wrapping the variable in sinle quotes causing mysql to read it as a string rather than a number.
Hope this helps! :)

Insert Blobs in MySql databases with php

I am trying to store an image in the DataBase, for some reason it doesn't seem to work. Here's the structure of my table.
mysql> describe ImageStore;
+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| ImageId | int(11) | NO | PRI | NULL | |
| Image | longblob | NO | | NULL | |
+---------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)
And here is my query which inserts the image or at least thats what it should:
//Store the binary image into the database
$tmp_img = $this->image['tmp_name'];
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('$this->image_id','file_get_contents($tmp_image)')";
mysql_query($sql);
If I print the value of file_get_contents($tmp_image), then there is a tons of data on the screen. But this value doesn't get stored in the database and that is the issue that I'm facing.
Problem
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('$this->image_id','file_get_contents($tmp_image)')";
This creates a string in PHP named $sql. Forget about MySQL for a minute, because you're not executing any query yet. You're just building a string.
The magic of PHP means that you can write a variable name — say, $this->image_id — inside the double quotes and the variable still gets magically expanded.
This functionality, known as "variable interpolation", does not occur for function calls. So, all you're doing here is writing the string "file_get_contents($tmp_image)" into the database.
Solution (1)
So, to concatenate the result of calling file_get_contents($tmp_image), you have to jump out of the string and do things explicitly:
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";
(You can see even just from the syntax highlighting how this has worked.)
Solution (2)
Now the problem you have is that if the binary data contains any ', your query is not valid. So you should run it through mysql_escape_string to sanitize it for the query operation:
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";
Solution (3)
Now you have a really big string, and your database is getting bulky.
Prefer not storing images in databases, where you can help it.
To expand on Tomalak's comment, you can't run a function inside of quotes.
Try:
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('{$this->image_id}','".file_get_contents($tmp_image)."')";
try this:
$tmp_img = $this->image['tmp_name'];
$sql = "INSERT INTO ImageStore(ImageId,Image)
VALUES('$this->image_id','" . addslashes(file_get_contents($tmp_image)) . "')";
mysql_query($sql);
As mentioned you are just saving the string "file_get_contents($tmp_image)" into the db
but you need to run the function file_get_contents instead
dont forget to hash the image using a hashing algorithm such as base64_encode before saving it to the db.

Categories