1

I am having the most difficult time getting the results that I want. I have done a ton of research and I am just not getting it. I am very new to this, but did my research before posting this question.

Ok, so I have a table with these columns: user_id, my_music, my_movies, my_weather, my_maps, and my_news

Each columns except user_id will have either a 1 or 0. What I need to do is find out the value stored in the database for each column for a specific user.

Here is what I have so far - This is my config.php:

// These variables define the connection information for your MySQL database
$username = "dbo12345";
$password = "xxxxxx";
$host = "db12345.db.123.com";
$dbname = "db12345";

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();

Here is my admin.php file:

require("config.php"); 
if(empty($_SESSION['user'])) 
{
    header("Location: index.php");
    die("Redirecting to index.php"); 
}   

$userid = $_SESSION['user']['id'];
$sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = :userID"; //Note the removed semi-colon that was probably causing your error
$stmt = $db->prepare($sql);
$stmt = $db->bindParam(":userID", $userid);
$userid = $_SESSION['user']['id'];
$sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = :userID"; //Note the removed semi-colon that was probably causing your error
$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();

if ($result['my_music']) {
    $musicChecked = 'checked="checked"';
} else {
    $musicChecked = '';

}
if ($result['my_movies']) {
    $checked = 'checked="checked"';
} else {
    $checked = '';

}

How can I write the above code differently? I know there is a way and I am having trouble finding it.

Based on the results above I need to update some checkboxes, for example if my_music is 1 in the database then set the checkbox to checked. So I am doing this:

<input type="checkbox" name="mymusic" id="mymusic" <? echo $musicChecked;?> />
<input type="checkbox" name="mymovies" id="mymovies" <? echo $moviesChecked;?> />

If I need to add more info please let me know. Any and all help is greatly appreciated.

iamthestreets
  • 733
  • 1
  • 15
  • 38
  • 1
    Use `die(mysql_error());` to print the actual error, that will give you a clue. Perhaps the `;` at the end of the query is the culprit. – TJ- Aug 26 '14 at 14:04
  • I added that to my code and got this error `Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)` – iamthestreets Aug 26 '14 at 14:09
  • Is your mySql server up and running? Can you connect to the server using any other client (like MySqlWorkbench) ? – TJ- Aug 26 '14 at 14:12
  • Sounds like you either don't have mysql running or some application (e.g Skype) is blocking the ports that mysql uses. – R T Aug 26 '14 at 14:14
  • @iamthestreets see my answer below – meda Aug 26 '14 at 16:00

3 Answers3

1

You were really close, you did not fetch properly:

require("config.php"); 
if(empty($_SESSION['user']['id'])) 
{
    header("Location: index.php");
    die("Redirecting to index.php"); 
}   

$userid = $_SESSION['user']['id'];

$sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news 
        FROM user_preferences 
        WHERE user_id = :userID";

$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid);
$stmt->execute();

$result = $stmt->fetch();
  • You bind Params on the statement object not the connection
  • You fetch on the statement as well not the connection
  • fetchAll returns a 2 dimensional array if you want to see the content use var_dump not echo

<input id="mymusic"
       type="checkbox" 
       name="mymusic" 
       <?php echo ($result['my_music']==1 ? 'checked' : '');?>     
/>

<input id="mymovies"
       type="checkbox" 
       name="mymovies"  
       <?php echo ($result['mymovies']==1 ? 'checked' : '');?>
/>
meda
  • 45,103
  • 14
  • 92
  • 122
  • This does not show anything, but I think it is because it is returning a NULL value which is incorrect as the database value stored for my_music is 1 – iamthestreets Aug 26 '14 at 16:49
  • @iamthestreets oh my God, I just noticed you never execute it `$stmt->execute();` check my edit – meda Aug 26 '14 at 16:50
  • 1
    You are a life saver! I have another question about updating the HTML input checkbox based on the value in the database for each column - should I edit my original question? – iamthestreets Aug 26 '14 at 17:00
  • Yes you can update your post with the client side code, or ask new question for that, up to you. are you using ajax? – meda Aug 26 '14 at 17:40
  • I updated my post above. Can you take a look? I am not using ajax. – iamthestreets Aug 26 '14 at 18:10
  • That worked! I just wanted to confirm that I am not using the `while($row = $stmt->fetch()){ echo $row['my_music']; }` but instead am simply writing this: `$result = $stmt->fetch();` is that ok? – iamthestreets Aug 26 '14 at 19:49
  • yes if you expect only one row , then remove the loop! – meda Aug 26 '14 at 20:04
0

It could be the semi-colon at the end of $userid in the query. Shouldn't be needed.

Can I also recommend looking into PDO as it's much more secure, and the mysql_* functions are becoming outdated?

Edit: Just noticed you asked about PDO, so here's a quick tutorial.

$user = "root";
$pass = "";
$conn = new PDO('mysql:host=localhost;dbname=SCHEMA;', $user, $pass);

$sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news 
FROM user_preferences WHERE user_id = :userID"; //Note the removed semi-colon that was probably causing your error

$stmt = $conn->prepare($sql);
$stmt->bindParam(":userID", $userid);
$result = $stmt->fetchAll(); //or $stmt->fetch(); if one line
echo $result['my_music']; //replace my_music with the column name result you need
Corey Thompson
  • 398
  • 6
  • 18
  • Yes, I am looking into PDO, but it I have had not luck with it. If I could have a little guidance or example of code, I think that would help me out a lot. – iamthestreets Aug 26 '14 at 14:08
  • @iamthestreets Here you go: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers – R T Aug 26 '14 at 14:10
  • Converted your mysql into PDO roughly. Untested but should work. I added the connection info up the top as it's a bit different to what you might be used to. – Corey Thompson Aug 26 '14 at 14:14
  • @CoreyThompson Do I need to add the connection info if I am requiring the config.php which has my connection info? – iamthestreets Aug 26 '14 at 14:32
  • You don't, but you'll want to set the `$conn` variable in your config.php similar to `new PDO(connection info)` (as you're making a object of the PDO class, using the connection info - rather than a MySQL connection object... I actually forget how the old MySQL functions connect, but you'll still need to). – Corey Thompson Aug 26 '14 at 14:33
  • Ok so I made some changes and I am now receiving this error: `Fatal error: Call to undefined method PDO::bindParam()` – iamthestreets Aug 26 '14 at 14:41
  • Would you mind posting your code including the connection? (Replace schema/user/pass/address if you need to) - maybe to pastebin.com or another code pasting website? – Corey Thompson Aug 26 '14 at 14:43
  • here is my config.php file: [link](http://pastebin.com/AvbRHAJ4) and my admin.php file: [link](http://pastebin.com/a5xa25kz) is this what you needed? Should I update my original question? – iamthestreets Aug 26 '14 at 15:01
  • Yeah you should update your original question, also add the tag PDO. To your code, can you change the last line to: `echo $db->fetchAll() or die(PDOException);` – Corey Thompson Aug 26 '14 at 15:07
  • Update my original question. I added what you said but still getting this error: `Fatal error: Call to undefined method PDO::bindParam()` – iamthestreets Aug 26 '14 at 15:21
  • My bad, I made a mistake in the last 3 lines of my code. If you check my updated answer now, it should work properly. – Corey Thompson Aug 26 '14 at 15:27
  • I made the changes and I am just getting this on the page: `PDOException` – iamthestreets Aug 26 '14 at 15:37
  • Apparently you can't get into chat, so instead, this should be the solution: `$result = $stmt->fetchAll();` then `echo $result["my_music"];` (replace my_music with your column) – Corey Thompson Aug 26 '14 at 15:40
  • I tried that and it says iamthestreets has only 5 reputation, not yet enough to chat – iamthestreets Aug 26 '14 at 15:41
  • Ok, so the page loaded with no errors but I don't see the echo of the results on the page – iamthestreets Aug 26 '14 at 15:53
  • Most likely this is because the SQL query doesn't return any results (e.g. the userid used doesn't have any data, or there isn't a stored value for my_music column, etc). Can you double check by: 1. Substitute a real value userid instead at `$stmt->bindParam(":userID", "REALID")` and make sure through another SQL client like Workbench or something that there is data for that user in the column/row? – Corey Thompson Aug 26 '14 at 15:56
  • I am using var_dump and it is displaying NULL. I had to change it to this: `$stmt->bindParam(":userID", $user_id = 44);` I checked the database and the user_id that i am using has a value stored in this column – iamthestreets Aug 26 '14 at 16:39
0

user_id is not guaranteed to be a number, is it? So put it between '. And you have a semicolon on the end of your query. The new query becomes:

$query = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = '".$userid."'";
sridesmet
  • 875
  • 9
  • 19