I'm sorry, probably somewhere there will be the answer to my question, but it's hours I'm looking for trying to resolve this problem:
Here is the code:
<?php
$con = mysql_connect("****","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$query = "SELECT id FROM fq_questions";
$rowcnt = mysql_num_rows(mysql_query($query));
echo "Tot scenes: ".$rowcnt;
$id = rand (1,$rowcnt);
echo "<br>Id rand: ".$id."<br>";
flush();
$newquery = "SELECT question FROM fq_questions WHERE id=".$id;
$result = mysql_query($newquery);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $newquery;
die($message);
}
$row = mysql_fetch_assoc($result);
echo $row['question'];
mysql_close($con);
?>
The problem is that there is no output. I've tried everything, seems to be a problem into the query, but there is a result, it's not false, but even if it exists, nothing is outputted.
The code works till
echo "<br>Id rand: ".$id."<br>";
then it shows nothing.
It's a dummy problem, i'm getting crazy just because of it.
Uh, was forgetting... The website where I've got the problem: http://www.freelabs.it/filmquiz/game.php
Be careful, desc is a SQL keyword ! Your query may not compile because of that.
"desc" is a MySQL reserved word, you should just change that column name in your DB. Anyway, your method is not random at all, and it will fail as soon as you have a "hole" in your ids (when you delete one member).
Take a look at MySQL "ORDER BY RAND()"
$data = mysql_query("SELECT description FROM fq_questions ORDER BY RAND() LIMIT 1");
You used mysql_fetch_row() which returns a numerical array. You then try to access the array slot named 'desc'.
It doesn't exist. (My guess is that that produces a supressed error, preventing any output from showing up, or a supressed warning, preventing any output after that line from showing up.)
Try changing mysql_fetch_row() to mysql_fetch_assoc() (still DEPRECATED!) and that should be solved.
Sources: http://php.net/manual/en/function.mysql-fetch-row.php
And: http://php.net/manual/en/function.mysql-fetch-assoc.php
Related
trying to get my head around this MySQL jibberish, lol - now I do not normally ask for help but on this one I think I do need a shove.
I have searched for the answers to this however the solutions are all based around the askers duplication of the fetch_array command, however I have not done this but still this code skips the first entry.
Can someone point out what I have done here that causes this to skip...?
code:
$link = mysqli_connect('localhost','person','password', 'database'); // connect to database
if (!$link) { die('Could not connect to MySQL: ' . mysqli_connect_error()); } // problem, then die
$sql = "SELECT * FROM id_info_db"; // Query construct
$result = mysqli_query($link, $sql); //query action
while ( $row = mysqli_fetch_array($result) ) { // print out rows
echo "User: " . $row["username"]. " - Password: " . $row["password"]. " " . $row["email"]. "<br>"; }
mysqli_close($link);
For some reason I had a loose /body tag at the end? why I don't know but it generated this result. Now I have deleted it the output is correct.
A remnant that should have been deleted that throws up an unfathomable error. Lol
I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.
I'm a beginner and trying to get a handle on php. I have been getting a syntax error that I can't seem to solve. I'll show you the code below and some of the fixes I've tried. If anyone has another idea that would be wonderful. Thank you:)
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("Database query failed: " . mysql_error());
}
while($subject = mysql_fetch_array($subject_set)) {
echo "<li> {$subject['menu_name']} </li>";
}
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = {$subject["id"]}", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
echo "<ul class='pages'>";
while($page = mysql_fetch_array($page_set)) {
echo "<li> {$page['menu_name']} </li>";
}
echo "</ul>";
I get: Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " at line 1
I know the problem is at {$subject["id"]} because I got content back and no error when I put "WHERE id_subjects = 1". I've tried:
{$subject['id']}
{$subject[\"id\"]}
But have gotten the same error...
try
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = '".$subject["id"]."'", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
BTW. you should really move away from mysql_* functions. They are being deprecated, move to PDO or mysqli_*, which are a lot safer as well (you are now vulnerable to sql injection)
If you read back to your post, you can clearly see what's going wrong here.
"SELECT * FROM pages WHERE id_subjects = {$subject["id"]}"
As you can see "id" is not connected to the rest of the rest. That is because with the " you close the string.
To fix this simply use
"SELECT * FROM pages WHERE id_subjects = " . $subject["id"]
Or if you really want to put the variable within the string you can use a single quoted string for the key:
"SELECT * FROM pages WHERE id_subjects = {$subject['id']}"
Personally I am a fan of the first solution. But that is just my opinion.
Well when the while loop finishes looping through, it will have exhausted all the results. $subject['id'] won't have any information simply because $subject no longer has any more entries.
I'm guessing you want to list all the subjects first, then all the pages underneath each subject.
Using mySQL isn't going to be pretty but here's what you want to do. (As Bono said use PDO or mysqli, but here's a solution in psuedocode that will work with mySQL).
loop through first query
print subject name
select pages using subject id
loop through pages under that subject id
print page names
You don't need any quotes when inside a quoted string, just use
"SELECT * FROM pages WHERE id_subjects = {$subject[id]}"
I am attempting to search a SQL table from a PHP script. the SQL table is a word list and in the PHP I call a Python script to do the permutations of a given word. Everything is working until I actually go to execute the mysql_query. I need some formatting advice on how to pass so many values to a Select statement. From what I've seen it needs to be in the form ('a','b','c',...) and this is how it is formatted but I'm not getting a return on the actual execution.
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$con= mysql_connect("127.0.0.1","app","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordlookup");
//Retrieve the data.
$word = $_POST['data'];
$perm = exec("python comb.py $word");
$query="SELECT * FROM words WHERE IN (" .$perm. ")";
print $query;
$sql=mysql_query($query);
print $sql;
mysql_close($con);
?>
This is all of the PHP file, the output from the python call would be in the 'a','b','c'... format and the random prints are just debugging. The print $sql doesn't actually put out anything at the moment.
Thanks,
Kyle
SELECT * FROM words WHERE IN (...)
Your query is missing a condition. WHERE what IN ...? You need to fill in a column name there.
Further, if a query is not working, ask the database why it didn't work:
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
Though solution is strange (use external script executed via exec to calculate permutations?), I'd answer your exact question.
$perm_arr = explode(' ', $perm);
function quote($str) { return "'$str'"; }
$perm_arr = array_map('quote', $perm_arr);
$sql = "select * from words where word in (" . join(', ', $perm_arr) . ")";
I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()