What is wrong with this PHP script? - php

<?php
$url = $_GET['url'];
if($url == "") {
die("Invalid Request! Missing Parameter 1!");
exit;
}
$tags = get_meta_tags($url);
$key = $tags['keywords'];
$desc = $tags['description'];
$con = mysql_connect('HOST', 'USER', 'PASS') or die(mysql_error());
mysql_select_db('zach_WebLock', $con) or die(mysql_error());
$query = "INSERT INTO `Keyword` (`Site`, `Keyword`, `Description`) VALUES ('".$site."', '".$key."', '".$desc."')";
mysql_query($query) or die(mysql_error());
echo '<b>Site: <u>'.$url.'</u></b>';
echo '<br>';
echo '<b>Description:</b>';
echo '<br>';
echo $desc;
echo '<br><br>';
$keys = explode(',', $key);
foreach($keys as $word) {
echo $word;
echo '<br>';
}
?>
This script extracts the keywords and description for the URL in the ?url= variable. It displays all the information, doesn't raise any errors but doesn't write the information to the DB. Any ideas? (
(I have left out the mysql_real_escape_string() for testing)

You're trying to insert the variable $site which is not defined. Perhaps you meant $url?
If that's not the case, please provide more information. Do you get any output from mysql_error()?

You need to add '' to allow for the AUTO INCREMENTATION for your primary key in the KeyWord table, which should stop the MySQL Error from occuring.
$query = "INSERT INTO 'Keyword' VALUES ('','$site', '$key', '$desc')";
echo $query;
If that doesn't fix your solution, I'd recommend echoing out the query when you run the script and look any blank values, fix where necessary. If you're still having issues copy paste the your expected INSERT Query that was echoed from the script and test it in PhpMyAdmin and see if you get a different result (errors).

Related

PHP - Upload data to database using a loop

I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array.
As such:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
}
var_dump($selected);
The above code is working and when I open it in my browser I get this output
Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:
foreach ($selected as $player){
$sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")')
or die(mysql_error());
print ($player);
echo'<br>';
` }
Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows:
If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.
Thanks in advance.
You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.
use this:
'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'
instead of this:
'INSERT INTO `team`(`player_name`) VALUES ("$player")'
Just replace following code with your ones code and it will work efficiently.
foreach ($selected as $player){
$sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')")
or die(mysql_error());
echo "$player<br />";
}

MySQL SELECT query seems to skip spaces

I'm a beginner with PHP and mySQL and I'm using it for my project. I sort of have a problem with my query.
This is my code:
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
do
{
foreach ($doctnamerow as $cell)
{
$doctnamerowvalue = $cell;
}
} while ($doctnamerow = mysql_fetch_row($doctname));
So the problem I have is that if the doctor's name has a space between it (e.g "AJ Ramos") then it seems to skip the space and just returns "AJ" and not the surname. How do I do this? Thanks =)
edit:
Silly me, It was just an error with my code, I was using $doctnamerowvalue as a value=$doctnamerow for one of my text boxes and forgot to put double quotes, which resulted in value=doctor name and not value="doctor name". Sorry
Flash Code Review:
mysql_* is deprecated. Use MySQLi or PDO.
Your code is wide open to SQL injection
$doctornamerowvalue is overwritten on every iteration
the foreach you are doing is pointless.
variable names are poorly chosen.
Here it is refactored:
// do these in a config file !!!
$db = new PDO('mysql:dbname=' . DB_NAME . ';host=localhost', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // if you want to use associative arrays
// here is the refactored code
$query = "SELECT name_of_doctor FROM `{$table}` WHERE department_no = :deptno";
$stmt = $db->prepare($query);
$stmt->execute(array(':deptno' => $_REQUEST['deptno']));
$doctors = $stmt->fetchAll();
foreach ($doctors as $doctor) {
echo $doctor['name_of_doctor'] . '<br>';
}
Related to your 'bug'
Check the table structure and data. It's possible that the field contains only the surname, and there is another field that contains the name.
Check the table length - maybe it's too small, so the string is truncated.
try this:
$sql = "your sql syntax";
$result = mysql_query($sql);
$array_of_things = array();
while ($row = mysql_fetch_array($result)) {
$array_of_things[] = $row['table_column_name'];
}
foreach($array_of_things as $val) {
echo $val;
}
used this :
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
while ($raw = mysql_fetch_row($doctname)) {
echo $raw['name_of_doctor'];
}

online server wont show string values

i have this code, where i get an array and make it a string, on my localhost show the values correctly (1,2...) but on my online server shows (,,) no numbers, just the commas. Does someone know what this issue may be?
Heres my code
<?php
error_reporting(E_ALL);
CONECTION
$sql = "select id from table where id=1";
$result = mysql_query( $sql);
$myArray= array() ; //Here you must declare it as array
while($row = mysql_fetch_array($result)){
$popurl = $row['id '];
$myArray[] = $popurl;
}
$string = "" . implode(", ", $myArray) . "" ;
echo $string;
?>
Please need help
It's a simple typo problem:
$row['id '] is not defined. Correct it to $row['id'] and you should be fine.

MySQL not fetching correct data? (PHP)

This is pretty straight forward.
EDIT: Updated question and added fourth echo.
Here is PHP code:
<?php
$ratings="3";
$item="Inception";
$query="SELECT * FROM items WHERE item = '". $item ."' LIMIT 1";
echo $query;
echo "<br />";
$result=mysql_query($query);
echo $result;
echo "<br />";
while ($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
echo $item_id;
echo "<br />";
}
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
echo $query_two;
$sql = mysql_query($query_two);
mysql_close();
?>
Here is web output with all the echo's:
SELECT * FROM items WHERE item = 'Inception' LIMIT 1
Resource id #7
INSERT INTO ratings (rating, item_id), VALUES (' 3 ', ' ')
How come my $item_id is blank? (third row underneath Resource id)
This part of code produces it:
$result=mysql_query($query);
echo $result;
It shows Resource... because it is of resource type, it's just a sort of special handler for query, it's not like normal type (string or int for example), so it has nothing readable to print.
If you want to print data from query then you must firstly fetch it.
Also note that those mysql_* functions are deprecated, it is discouraged to use them. Note from php manual:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information. Alternatives to this function
include:
mysqli_query()
PDO::query()
This does not have anything to do with IDs from the database.
This (Result#7) says that this result resource is seventh resource to be created by your php script execution.
Also
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
should be
$query_two = "INSERT INTO ratings (rating, item_id) VALUES (' {$ratings} ', ' {$item_id} ')";
You have comma before VALUES.
Also, it seems that $item_id is blank. Please check DB whether you have data for item = 'Inception'.
Regarding, Result#7 please follow others answers.
The Resource ID is coming from the actual process/object that the MySQL Query is.
to return the result you need:
$row = mysql_fetch_array( $query );
echo $row['item']
You need to do something with the result resource. Try this:
$result=mysql_query($query);
//echo $result;
$result_array = mysql_fetch_assoc( $result );
print_r( $result_array );
EDIT: I see you updated your question.
You should run your item='Inception' query directly in MySQL to confirm that results are what you expect.
You cannot echo the result that simple. You need to fetch the result to for example an array:
while ($row = mysql_fetch_array($query)) {
echo $row['a_column'] . "<br />";
}
or an object:
while ($variable = mysql_fetch_object($query) {
$value = $variable->a_column;
}
echo $value;
There are more ways but this is just two examples

while loop within foreach

I've got a form with questions which gets answered. Then on the following page I'm trying to validate the questions to see if the answer is correct or not because eventually I must work out a percentage for the test.
$tid1 = $_SESSION['tid'];
$departmentid = $_SESSION['deptid'];
$userid = $_SESSION['userid'];
foreach($_POST['question'] as $key => $answer) {
include 'datalogin.php';
mysql_query("INSERT INTO ex_answer (id,class_name,testname,name,percentage,qnr,answer_chosen,points_scored,result)
VALUES ('0','$departmentid','$tid1','$userid','0','$key','$answer[0] $answer[1] $answer[2] $answer[3] $answer[4] $answer[5] $answer[6] $answer[7] $answer[8]','0','0')");
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid1' AND q_nr = '$key'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1)) {
$q_nr=$row1['q_nr'];
echo $q_nr;
}
}
The problem is (I think) that it is not selecting the question number q_nr = '$key' correctly from the table because echo $q_nr gives no output
If you are getting a valid result (Test the sql in your Database client ) then you should just use the following to access it as an associative array:
mysql_fetch_assoc($result1);
instead of the mysql_fetch_array() or use
mysql_fetch_array($result1, MYSQL_ASSOC)
Test what is being returned to you, comment out your while loop and then do:
$row1 = mysql_fetch_array($result1);
print_r($row1);
before you while loop add the following for validation:
if (!$result1) {
die('Could not query:' . mysql_error());
}
Use mysql_fetch_assoc to be able to use column name indexes on returned array.
You can also output the SQL and test it on the DB, that will show that you are getting the expected results

Categories