Ok, I can't figure out why this doesn't work at all.
$get_data = mysql_query("SELECT * FROM chatbox ORDER BY ID WHERE message = 'bla'");
while($data = mysql_fetch_assoc($get_data)) {
*blablabla code*
}
This does NOT work. It gives me a
"Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource" error. (with line number ofcourse)
When I remove the "WHERE message = 'bla'" part, it works fine. Tryed with and without ' things around bla and around messages. Message field does excist in my DB, so does the entry bla. Tryed it even with the ID field in my DB, with number 1, does not work at all. What is wrong with this simple line of code. Tryed to look almost everywhere, can't figure it out...
You are using WHERE clause after ORDER BY, it can not be work for you.
Modified Query:
SELECT * FROM chatbox WHERE message = 'bla' ORDER BY ID
You need to follow this sequence when you crease MYSQL SELECT Statement:
SELECT .. COLUMNS .. FROM .. WHERE .. ORDER
SELECT Manual Reference
Side Note:
Please use mysqli_* or PDO instead of mysql_* because this extension deprecated and not available in PHP 7.
Your query is wrong. You are using order by before where condition.
Try this query : "SELECT * FROM chatbox WHERE message = 'bla' ORDER BY ID"
And also migrate from mysql_* to mysqli_*.
Related
I checked other questions, PHP and PDO documentation and many other examples, but I feel stuck, probably since I'm just getting started with PHP and MySQL.
I'm trying to first check if a line exist with a SELECT statement and then if line exists DELETE it.
However, the query is not going through, I'm using MySQL 8 on Ubuntu 18, and the queries work only with the single quotes after the WHERE clause:
SELECT bookname FROM libri WHERE bookname LIKE "test.pdf";
DELETE FROM libri WHERE bookname LIKE "test.pdf";
However seems like i'm unable to reproduce it with the prepared statements:
$sql = "SELECT bookname FROM libri WHERE bookname LIKE :deleteTerm;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':deleteTerm', $deleteKey);
$stmt->execute();
I set $deleteKey as $deleteKey = $_POST['delete']; and trying to attach the single quotes as $stmt->bindValue(':deleteTerm', "'".$deleteKey."'"); it's not working.
Also tried to set quotes directly into variable name: $deleteKey = "'".$_POST['delete']."'"; and using the prepared statement above, but still not working.
Am i missing something,or getting something wrong? Maybe I have to use another query?
"select" part of the transaction you have done is unnecessary. because you mean delete it if it exists. you are trying to delete it in the next section. if you actually run the second part directly, it will delete it if it already exists.I also recommend you to try this in the clawed area.
$sql = " DELETE FROM libri WHERE bookname LIKE 'test.pdf'";
In my test-surroundings there is a database containing some Person Information (Name, E-Mail, Adress etc.). These Informations can be inserted by anyone into the database via a form. In the background they are inserted with a parameterized INSERT into the database after submission.
What I now would like to do is to detect if some person tries to insert the same values into the database again, and if he does, not inserting the new values and instead showing an error message. (So every person name in the database is unique, there are no multiple rows linked to one name).
I had a numerous number of ideas on how to accomplish this. My first one was to use a query like REPLACE or INSERT IGNORE, but this method would not give me feedback so I can display the error message.
My second attempt was to first do a SELECT-query, checking if the row already exists, and if num_rows is greater than 0, exit with the error message (and else do the INSERT-part). For this to work I will have to use parameterized queries for the SELECT too, as I´m putting some user input into it. Figuring that parameterized queries need special functions for everything you could normally do with way less lines of code, I researched in the internet on how to get num_rows from my $statement parameterized-statement-object. This is what I had in the end:
$connection = new mysqli('x', 'x', 'x', 'x');
if (mysqli_connect_error()) {
die("Connect Error");
}
$connection->set_charset("UTF-8");
$statement = $connection->stmt_init();
$statement = $connection->prepare('SELECT Name FROM test WHERE Name LIKE ?');
flags = "s";
$statement->bind_param($flags, $_POST["person_name"]);
$statement->execute();
$statement->store_result();
$result = $statement->get_result(); //Produces error
if ($result->num_rows >= 1) {
$output = "Your already registered";
} else {
$output = "Registering you...";
}
exit($output);
After all, I can´t get why mysqli still won´t give me num_rows from my statement. Any help is appreciated, thanks in advance!
Oh, and if you guys could explain to me what I have to do to get affected_rows,that would be awesome!
EDIT: I know I could to this by using unique constraints. I also found out that I can find out if INSERT IGNORE skipped the INSERT or not. But that won´t answer my complete question: Why does the SELECT num_rows alternative not work?
ANOTHER EDIT: I changed the code snippet to what I now have. Although my mysql(i)-version seems to be 5.6.33 (I echo´d it via $connection->server_info) get_result() produces the following error message:
Fatal error: Call to undefined method mysqli_stmt::get_result() in X on line X (line of get_result)
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. Note that if the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.
Also make sure that you declare ->store_result() first. Moreover the function doesn't work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually.
EDIT:
If nothing from the suggestions does not work for you, then I would propose to rewrite your SQL query:
SELECT `Name`, (SELECT COUNT(*) FROM `Persons`) AS `num_rows` FROM `Persons` WHERE `Name` LIKE ?
This query will return the total number from your Persons table, as well as Name, if exist.
I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");
I'm trying to get the right syntax for the following. In this case $post_pub = 1
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL" FROM "Publications" where "Pub_ID"="$post_pub"';
Php throws an error: column "$post_pub" does not exist
I've stumbled across pg_query_params, this feels like the right direction, but I need some help. How can I get this to work?
I never used pg_connect though I think you need something like this:
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL"
FROM "Publications"
where "Pub_ID"=$1 ';
$result = pg_query_params($dbconn, $sql, array($post_pub));
the problem is double quotes around variable. Postgres understands it as "database object" name, in this part of query, a column. to avoid it, try using:
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL" FROM "Publications" where "Pub_ID"='."$post_pub";
also consider moving to PDO - such usage is a straight invitation for sql injection. Setting$post_pub to 0 or (delete from Publications)" will delete all data if user has enough right, for example.
I have this database I created with a phpMyAdmin client. Specific queries like SELECT * FROM TagData LIMIT 0,10 in my php code runs perfect. But when I add a wildcard to the query like SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10 it doesn't work. The strange thing is that the exact same SQL works perfect in the phpMyAdmin tool.
This is how I run my query in php:
$query="SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10";
$tmpResult=mysql_query(sprintf($query));
I have a strong feeling that the quote characters in the $query string are the problem. Can someone please explain me what I am doing wrong and why I am doing this wrong.
The result mysql_error() gives is:
Query was empty
You dont need sprintf when you dont insert any custom parameters.
Just leave it raw.
Your query was emtpy because the string you gave to sprintf was malformed and sprintf returned null/ an empty string.
You need parameters to place in sprintf otherwise this has no use. And % is a control character for sprintf, to escape this you would have to place %% instead of % but my advice here ins aslong as you do not have any parameters, just dont use it!
To make your query work just fire it raw
$query= "SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10";
$tmpResult = mysql_query($query);
And now, please have a look what sprintf actually does:
http://php.net/manual/en/function.sprintf.php
However please consider upgrading to MySQLi or PHP/PDO extension because MySQL class is outdated, deprecated, unsave, slow and will be removed from PHP in the future.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php